When I press the sync button, I need to run the Check Routine function. How can I do this ?
const CheckRoutine = require('../routines/check-at');
export default ({ className }) => (
<ul className={ `nav flex-column ${className || ''}` }>
<li>
<button className="btn btn-primary"
onClick={CheckRoutine} >
<i className="fa fa-refresh"> </i>
<span>Sync</span>
</button>
</li>
</ul>
);```
check-at:
module.exports = atCheck;
function atCheck() {
console.log("Cheking...");
}
If your check Routine is in the same component, you can directly give,
<button className="btn btn-primary"
onClick={CheckRoutine} >
<i className="fa fa-refresh"> </i>
<span>Sync</span>
</button>
or If your Check routine is in parent component, you can use call back function inside your component like below.
const CheckRoutine =(event) =>{
event.preventDefault();
props.checkRoutine();
}
<button className="btn btn-primary"
onClick={CheckRoutine} >
<i className="fa fa-refresh"> </i>
<span>Sync</span>
</button>
you can use this,
CheckRoutine.js
const CheckRoutine = e => {
console.log(e)
}
export default CheckRoutine
fileName.js
import CheckRoutine from './CheckRoutine'
export default ({ className }) => (
<ul className={ `nav flex-column ${className || ''}` }>
<li>
<button className="btn btn-primary"
onClick={CheckRoutine} >
<i className="fa fa-refresh"> </i>
<span>Sync</span>
</button>
</li>
</ul>
);
or you can in single file
const CheckRoutine = e => {
console.log(e)
}
export default ({ className }) => (
<ul className={ `nav flex-column ${className || ''}` }>
<li>
<button className="btn btn-primary"
onClick={CheckRoutine} >
<i className="fa fa-refresh"> </i>
<span>Sync</span>
</button>
</li>
</ul>
);
import atCheck from '../routines/check-at'
export default ({ className }) => (
<ul className={ `nav flex-column ${className || ''}` }>
<li>
<button className="btn btn-primary"
onClick={atCheck} >
<i className="fa fa-refresh"> </i>
<span>Sync</span>
</button>
</li>
</ul>
);
//../routines/check-at
export default const atCheck => (e) {
console.log("Cheking...");
}
Related
I am making a newsapp i want it to have different categories, instead of using react-router-dom for navigation what i want to do is create a state object and create a key in it named category and set current category as it's value and i have sent that key as a props to news component where i fetch news and embed that category to the fetch URL
I have made a function to set the category and its in app.js I have sent it to navbar component as props, the issue i am facing is that i can't select a category, because for some reason the onClick of the very last category is being called continuously and I know this because I console logged the category in setCategory function, can anyone tell me why this is happening
code in app.js:
import './App.css';
import React, { Component } from 'react'
import Navbar from './components/Navbar';
import News from './components/News';
export default class App extends Component {
constructor() {
super()
this.state = {
darkMode: "light",
country: "us",
category: "general",
key: "general"
}
}
setCategory = (cat)=> {
this.setState({
category: cat
})
console.log(this.state.category)
}
setCountry = (cntry)=> {
this.setState({
category: cntry
})
}
setDarkMode = () => {
if (this.state.darkMode === "light") {
this.setState({ darkMode: "dark" })
document.body.style.backgroundColor = "black"
} else {
this.setState({ darkMode: "light" })
document.body.style.backgroundColor = "white"
}
}
render() {
return (
<div>
<Navbar setCategory={this.setCategory} setCountry={this.setCountry} setDarkMode={this.setDarkMode} darkMode={this.state.darkMode} />
<News key={this.state.category} category={this.state.category} country={this.state.country} pageSize={18} darkMode={this.state.darkMode} />
</div>
)
}
}
code in Navbar component:
import React, { Component } from 'react'
export default class Navbar extends Component {
constructor(props) {
super(props)
this.setCategory = this.props.setCategory
}
render() {
return (
<div>
<nav className={`navbar navbar-expand-lg navbar-${this.props.darkMode} bg-${this.props.darkMode}`}>
<a className="navbar-brand" href="/">NewsMonkey</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className="nav-item active">
<a className="nav-link" href="/">Home <span className="sr-only">(current)</span></a>
</li>
<li className="nav-item">
<a className="nav-link" href="/about">About</a>
</li>
<li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" href="/" role="button" data-toggle="dropdown" aria-expanded="false">
Categories
</a>
<div className="dropdown-menu">
<p className="dropdown-item cursor-pointer" onClick={this.setCategory("business")}>Business</p>
<p className="dropdown-item cursor-pointer" onClick={this.setCategory("science")}>Science</p>
<p className="dropdown-item cursor-pointer" onClick={this.setCategory("technology")}>Technology</p>
<p className="dropdown-item cursor-pointer" onClick={this.setCategory("entertainment")}>Entertainment</p>
<p className="dropdown-item cursor-pointer" onClick={this.setCategory("health")}>Health</p>
<p className="dropdown-item cursor-pointer" onClick={this.setCategory("sports")}>Sports</p>
<div className="dropdown-divider"></div>
<p className="dropdown-item cursor-pointer" onClick={this.setCategory("general")}>General</p>
</div>
</li>
</ul>
{/* <form className="form-inline my-2 my-lg-0">
<input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" />
<button className="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form> */}
<div className={`custom-control custom-switch text-${this.props.darkMode === "light" ? "dark" : "light"}`}>
<input type="checkbox" className="custom-control-input" onClick={this.props.setDarkMode} id="customSwitch1" />
<label className={`custom-control-label`} htmlFor="customSwitch1">Dark mode</label>
</div>
</div>
</nav>
</div>
)
}
}
This doesn't do what you think it does:
onClick={this.setCategory("business")}
This calls the setCategory function immediately and uses the result of that function as the onClick handler. Don't pass the result of calling a function to onClick, pass a function itself:
onClick={() => this.setCategory("business")}
import React, { useEffect } from "react";
import Loader from "../layout/Loader";
import { useAlert } from "react-alert";
import { useDispatch, useSelector } from "react-redux";
import { getProductDetails, clearErrors } from "../../actions/productActions";
const ProductDetails = ({ match }) => {
const dispatch = useDispatch();
const alert = useAlert();
const { loading, error, product } = useSelector((state) =>
state.productDetails()
);
useEffect(() => {
dispatch(getProductDetails());
if (error) {
alert.error(error);
dispatch(clearErrors());
}
}, [dispatch, alert, error]);
return (
<>
{!loading ? (
<Loader />
) : (
<>
<div className='row f-flex justify-content-around'>
<div className='col-12 col-lg-5 img-fluid' id='product_image'>
<img
src='https://i5.walmartimages.com/asr/1223a935-2a61-480a-95a1-21904ff8986c_1.17fa3d7870e3d9b1248da7b1144787f5.jpeg?odnWidth=undefined&odnHeight=undefined&odnBg=ffffff'
alt='sdf'
height='500'
width='500'/>
</div>
<div className='col-12 col-lg-5 mt-5'>
<h3>{product.name}</h3>
<p id='product_id'>Product # sklfjdk35fsdf5090</p>
<hr />
<div className='rating-outer'>
<div className='rating-inner'></div>
</div>
<span id='no_of_reviews'>(5 Reviews)</span>
<hr />
<p id='product_price'>$108.00</p>
<div className='stockCounter d-inline'>
<span className='btn btn-danger minus'>-</span>
<input
type='number'
className='form-control count d-inline'
value='1'
readOnly
/>
<span className='btn btn-primary plus'>+</span>
</div>
<button
type='button'
id='cart_btn'
className='btn btn-primary d-inline ml-4'
>
Add to Cart
</button>
<hr />
<p>
Status: <span id='stock_status'>In Stock</span>
</p>
<hr />
<h4 className='mt-2'>Description:</h4>
<p>
Binge on movies and TV episodes, news, sports, music and more!
We insisted on 720p High Definition for this 32" LED TV,
bringing out more lifelike color, texture and detail. We also
partnered with Roku to bring you the best possible content with
thousands of channels to choose from, conveniently presented
through your own custom home screen.
</p>
<hr />
<p id='product_seller mb-3'>
Sold by: <strong>Amazon</strong>
</p>
<button
id='review_btn'
type='button'
className='btn btn-primary mt-4'
data-toggle='modal'
data-target='#ratingModal'
>
Submit Your Review
</button>
<div className='row mt-2 mb-5'>
<div className='rating w-50'>
<div
className='modal fade'
id='ratingModal'
tabIndex='-1'
role='dialog'
aria-labelledby='ratingModalLabel'
aria-hidden='true'
>
<div className='modal-dialog' role='document'>
<div className='modal-content'>
<div className='modal-header'>
<h5 className='modal-title' id='ratingModalLabel'>
Submit Review
</h5>
<button
type='button'
className='close'
data-dismiss='modal'
aria-label='Close'
>
<span aria-hidden='true'>×</span>
</button>
</div>
<div className='modal-body'>
<ul className='stars'>
<li className='star'>
<i className='fa fa-star'></i>
</li>
<li className='star'>
<i className='fa fa-star'></i>
</li>
<li className='star'>
<i className='fa fa-star'></i>
</li>
<li className='star'>
<i className='fa fa-star'></i>
</li>
<li className='star'>
<i className='fa fa-star'></i>
</li>
</ul>
<textarea
name='review'
id='review'
className='form-control mt-3'
></textarea>
<button
className='btn my-3 float-right review-btn px-4 text-white'
data-dismiss='modal'
aria-label='Close'
>
Submit
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</>
)}
</>
);
};
export default ProductDetails;
As the error suggests
state.productDetails is not a function
This is because productDetails is a reducer object and Not a function created by redux. Hence, your code should be
const { loading, error, product } = useSelector((state) =>state.productDetails); //Note: productDetails without '()'
Hope it helps.
Side Note: While posting any question or answer please format the code properly next time so it's readable. :)
Could someone maybe explain why my map doesn't work in the template.
I tried 4 hours, but i didn't get a useful solution.
The render() works bevor i fetched all data from firebase
If i try to render the map again by using the setState Hook or in my case the setsalesList hook the templet doesn't render again.
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import NavBar from "./NavBar";
import { db } from "../firebase";
import { useAuth } from "../contexts/AuthContext";
const Sales = () => {
const [isLoading, setIsLoading] = useState(true);
const [salesList, setSalesList] = useState([]);
const { currentUser } = useAuth();
async function setupProject() {
let salesDataList = [];
await db
.collection("users")
.doc(currentUser.uid)
.get()
.then((userItemData) => {
const userItem = userItemData.data();
db.collection("projects")
.doc(userItem.project[0])
.get()
.then((projectData) => {
db.collection("sales")
.where("project", "==", projectData.id)
.get()
.then((sales) => {
sales.forEach((sale) => {
sale
.data()
.customer.get()
.then((customer) => {
let salesData = {
key: sale.id,
name: customer.data().name,
sold: sale.data().sold,
date:
new Date(sale.data().time.toDate()).getDate() +
"." +
new Date(sale.data().time.toDate()).getMonth() +
"." +
+new Date(sale.data().time.toDate()).getFullYear(),
};
salesDataList.push(salesData);
console.log(salesDataList);
});
});
setSalesList(salesDataList);
})
.finally(() => {});
});
});
setIsLoading(false);
}
useEffect(() => {
setupProject();
}, []);
return (
<>
<NavBar />
<div className="header header-fixed header-logo-center">
<a className="header-title">Verkäufe</a>
<a href="https://huehnerpi.de/customer" className="header-icon">
<i className="fas fa-user" />
</a>
<a
href="https://huehnerpi.de/sales/newSale"
className="header-icon header-icon-4"
>
<i className="fas fa-plus" />
</a>
</div>
{isLoading ? (
<div className="page-content header-clear-medium">
<div
className="content mt-0"
style={{
marginBottom: 16,
marginLeft: 16,
marginRight: 16,
}}
>
<p>Lädt...</p>
</div>
</div>
) : (
<div className="page-content header-clear-medium">
<div
className="card card-style"
style={{
marginBottom: "16px",
}}
>
<div className="content mb-0">
<div className="input-style input-style-always-active has-borders no-icon">
<select
id="dropdownStatus"
style={{
color: "darkslategray",
}}
>
<option value="all">Alle Status</option>
</select>
<span>
<i className="fa fa-chevron-down" />
</span>
<i className="fa fa-check disabled valid color-green-dark" />
<em />
</div>
<div className="input-style input-style-always-active has-borders no-icon">
<select
id="dropdownCustomer"
style={{
color: "darkslategray",
}}
>
<option value="all">Alle Käufer</option>
</select>
<span>
<i className="fa fa-chevron-down" />
</span>
<i className="fa fa-check disabled valid color-green-dark" />
<em />
</div>
</div>
</div>
{console.log(salesList.length)}
{salesList.map((saleItem) => (
<a
key={saleItem.key}
className="card card-style mb-3 filterDiv"
style={{ display: "block" }}
>
<div className="content">
<h3>
{saleItem.name} - {saleItem.sold} Eier
<span data-menu="menu-contact-2" style={{ float: "right" }}>
<span className="icon icon-xxs rounded-sm shadow-sm me-1 bg-red-dark">
<i className="fas fa-times" />
</span>
</span>
<span style={{ float: "right" }}>
<span className="icon icon-xxs rounded-sm shadow-sm me-1 bg-blue-dark">
<i className="fas fa-pen" />
</span>
</span>
</h3>
<div className="row mb-n2 color-theme">
<div className="col font-10 text-start">
<span className="badge bg-green-dark color-white font-10 mt-2">
Bezahlt
</span>
</div>
<div className="col font-10 text-end opacity-30">
<i className="fa fa-calendar pe-2" />
12.12.2020 <span className="copyright-year" />
</div>
</div>
</div>
</a>
))}
</div>
)}
</>
);
};
export default Sales;
In this way it worked now for me!
I set the state after the last iteration of my foreach
import {Link} from "react-router-dom";
import NavBar from "./NavBar";
import {db} from "../firebase"
import {useAuth} from "../contexts/AuthContext";
const Sales = () => {
const [isLoading, setIsLoading] = useState(true);
const [salesList, setSalesList] = useState([]);
const { currentUser } = useAuth();
function setupProject() {
let salesDataList = [];
db.collection("users").doc(currentUser.uid).get()
.then(userItemData => {
const userItem = userItemData.data();
db.collection("projects").doc(userItem.project[0]).get()
.then(projectData => {
db.collection("sales").where("project", "==", projectData.id).get()
.then((sales) => {
let i = 0;
sales.forEach((sale) => {
sale.data().customer.get()
.then(customer => {
let salesData = {
key: sale.id,
name: customer.data().name,
sold: sale.data().sold,
date: new Date(sale.data().time.toDate()).getDate() + "." + new Date(sale.data().time.toDate()).getMonth() + "." + + new Date(sale.data().time.toDate()).getFullYear(),
};
salesDataList.push(salesData)
if (sales.size -1 === i++) {
setSalesList(salesDataList);
setIsLoading(false);
}
})
});
});
});
});
}
useEffect(() => {
setupProject();
}, []);
return(
<>
<NavBar />
<div className="header header-fixed header-logo-center">
<a className="header-title">Verkäufe</a>
<i className="fas fa-user"/>
<i className="fas fa-plus"/>
</div>
{isLoading ? (
<div className="page-content header-clear-medium">
<div className="content mt-0" style={{
marginBottom: 16,
marginLeft: 16,
marginRight: 16
}}>
<p>Lädt...</p>
</div>
</div>
) : (
<div className="page-content header-clear-medium">
<div className="card card-style" style={{
marginBottom: "16px"
}}>
<div className="content mb-0">
<div className="input-style input-style-always-active has-borders no-icon">
<select id="dropdownStatus" style={{
color: "darkslategray"
}}>
<option value="all">Alle Status</option>
</select>
<span><i className="fa fa-chevron-down"/></span>
<i className="fa fa-check disabled valid color-green-dark"/>
<em/>
</div>
<div className="input-style input-style-always-active has-borders no-icon">
<select id="dropdownCustomer" style={{
color: "darkslategray"
}}>
<option value="all">Alle Käufer</option>
</select>
<span><i className="fa fa-chevron-down"/></span>
<i className="fa fa-check disabled valid color-green-dark"/>
<em/>
</div>
</div>
</div>
{salesList.length > 0 && console.log(salesList.length)}
{salesList.map(saleItem => (
<a key={saleItem.key} className="card card-style mb-3 filterDiv" style={{display: "block"}}>
<div className="content">
<h3>{saleItem.name} - {saleItem.sold} Eier
<span data-menu="menu-contact-2" style={{float: "right"}}>
<span className="icon icon-xxs rounded-sm shadow-sm me-1 bg-red-dark">
<i className="fas fa-times"/>
</span>
</span>
<span style={{float: "right"}}>
<span className="icon icon-xxs rounded-sm shadow-sm me-1 bg-blue-dark">
<i className="fas fa-pen"/>
</span>
</span>
</h3>
<div className="row mb-n2 color-theme">
<div className="col font-10 text-start">
<span className="badge bg-green-dark color-white font-10 mt-2">Bezahlt</span>
</div>
<div className="col font-10 text-end opacity-30">
<i className="fa fa-calendar pe-2"/>12.12.2020 <span className="copyright-year"/>
</div>
</div>
</div>
</a>
))}
</div>
)}
</>
);
}
export default Sales;```
I want to add active class to the parent element of the div, but the problem is this code is adding on double click not on single click, how to fix this.
The below code is for the sidebar which I want to show on my website, everything is fine but the problem is the handleActiveClass function is not working on single click.
import React from 'react';
import { Link } from 'react-router-dom';
import './Sidebar.css';
const Sidebar = ({ sidebarOpen, closeSidebar, handleLogout }) => {
let logoUrl = JSON.parse(localStorage.getItem('app_icon'));
const handleActiveClass = (e) => {
e.target.parentElement.classList.toggle('active_menu_link');
};
return (
<div id='sidebar' className={sidebarOpen ? 'sidebar-responsive' : ''}>
<div className='sidebar_title'>
<div className='sidebar_img'>
<img src={`https://stucharge.bakersbrisk.com${logoUrl}`} alt='logo' />
<h1>Admin Panel</h1>
</div>
<i className='fa fa-times' id='sidebaricon' onClick={closeSidebar}></i>
</div>
<div className='sidebar_menu'>
<div className='sidebar_link ' onClick={(e) => handleActiveClass(e)}>
<i className='fa fa-home'></i>
<Link to='/home'>Dashboard</Link>
</div>
<h2>MNG</h2>
<div className='sidebar_link ' onClick={(e) => handleActiveClass(e)}>
<i className='fas fa-user-circle'></i>
<Link to='/profile'>Profile </Link>
</div>
<div className='sidebar_link ' onClick={(e) => handleActiveClass(e)}>
<i className='fas fa-book'></i>
<Link to='/subjects'>Subjects </Link>
</div>
<div className='sidebar_link ' onClick={(e) => handleActiveClass(e)}>
<i className='fa fa-graduation-cap'></i>
<Link to='/courses'>Courses</Link>
</div>
<div className='sidebar_link ' onClick={(e) => handleActiveClass(e)}>
<i className='fas fa-book-open'></i>
<Link to='/notes'>Notes</Link>
</div>
<div className='sidebar_link ' onClick={(e) => handleActiveClass(e)}>
<i className='fas fa-chalkboard-teacher'></i>
<Link to='/class'>Online Class</Link>
</div>
<div className='sidebar_link ' onClick={(e) => handleActiveClass(e)}>
<i className='fa fa-handshake-o'></i>
<Link to='/contact'>Contact Developer</Link>
</div>
<h2>LEAVE</h2>
<div className='sidebar_logout'>
<i className='fa fa-power-off'></i>
<Link to='/' onClick={handleLogout}>
Log out
</Link>
</div>
<div
className='dev'
style={{ position: 'absolute', bottom: '20px', left: '8px' }}
>
<h3 style={{ color: '#51c4d3' }}>
Developed by{' '}
<i
className='far fa-thumbs-up'
style={{ fontSize: '1.6rem', marginLeft: '4px' }}
></i>
</h3>
<h2 style={{ color: '#b0efeb' }}>Codeven Solution</h2>
</div>
</div>
</div>
);
};
export default Sidebar;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
This code might not run here, but you can understand it as i have pasted the whole code.
Hello everyone I need help regarding linking of pages in nextjs.
actually I know how to link but what i want is following:
I have my home page having course team contact links in navbar so when I click course then course page gets open with url "localhost:3000/course" and in that course page I have courses .
I want that by clicking on any course in course page it should get open and the url should be "localhost:3000/course/course_1".
what should I do ?
This is header component:
const Header = () => (
<div>
<nav className="navbar navbar-expand-lg navbar-dark" >
<Logo />
<button className="navbar-toggler" type="button" data-target="#navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse">
<ul className="navbar-nav">
<li>
<a href="/" className="nav-link" >Home</a>
</li>
<li>
<a href="/team" className="nav-link" >Team</a>
</li>
<li>
<a href="/courses" className="nav-link" >Course</a>
</li>
<li >
<a href="/contact" className="nav-link" >Contact</a>
</li>
</ul>
<form className="form-inline my-2 my-lg-0">
<div className="d-flex justify-content-center h-100">
<div className="searchbar">
<input className="search_input text-center" type="text" name="" placeholder="Search..." />
<i className="fas fa-search"></i>
</div>
</div>
</form>
</div>
</nav>
This is the course :
const Course = () => (
<div>
<div className="col-xs-12 col-sm-4">
<div className="card">
<a className="img-card img-part-2" href="#">
<img src="/static/course1-img.jpg" />
</a>
<div className="teacher-img">
<div className="ava">
<img alt="Admin bar avatar" src="http://ivy-school.thimpress.com/demo-3/wp-content/uploads/learn-press-profile/5/2448c53ace919662a2b977d2be3a47c5.jpg" className="avatar avatar-68 photo" height="68" width="68" />
</div>
</div>
<div className="card-content">
<p className="card-para">Charlie Brown </p>
<h4 className="card-title">
<a href="/Pyhton">
Learn Python – Interactive <br/> Python
</a>
</h4>
<div className="info-course">
<span className="icon1&-txt">
<i className="fas fa-user"></i>
3549
</span>
<span className="icon2&-txt">
<i className="fas fa-tags"></i>
education
</span>
<span className="icon3&-txt">
<i className="fas fa-star"></i>
0
</span>
</div>
</div>
</div>
</div>
You can try like this:
server.js
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('/course', (req, res) => {
return app.render(req, res, '/courses')
})
server.get('/course/:id', (req, res) => {
return app.render(req, res, '/course', { id: req.params.id })
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
course.js
import React, { Component } from 'react'
export default class extends Component {
static getInitialProps ({ query: { id } }) {
return { courseId: id }
}
render () {
return (
<div>
<h1>Course {this.props.courseId}</h1>
</div>
)
}
}
courses.js
import React, { Component } from 'react'
export default class extends Component {
render () {
return (
<div>
<a href="/course/python">
Learn Python – Interactive <br/> Python
</a>
<a href="/course/javascript">
Learn Javascript – Interactive <br/> Javascript
</a>
</div>
)
}
}