How to convert a React class-based component into a functional component? - javascript

Here is my code for a React "class" based component for a carousel slider that I want to convert into a functional component, but I don't understand how.
import React from "react";
import web from "../../image/nisha.jpg";
import web1 from "../../image/Pooja.jpg";
import web2 from "../../image/6547.jpg";
import "../../styles.scss";
import ReactReadMoreReadLess from "react-read-more-read-less";
export default class extends React.Component {
render() {
return (
<div>
<h1 className="blog_heading">Testimonials</h1>
<div className="testimonial">
<div
id="carouselExampleSlidesOnly"
className="carousel slide"
data-ride="carousel"
>
<div className="carousel-inner container">
<div className="carousel-item active">
<div className="testimonial_content">
<a href={web}>
<img
src={web}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1>Nisha Sinha</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "15px" }}
>
It's a big thanks for helping me a lot in achieving my
goal of JRF. All the lectues were so helpful and i really
learned from basic to the top and my doubts got cleared
whenever needed and really all the faculties helped with
quality videos ”
</ReactReadMoreReadLess>
</p>
</div>
</div>
<div className="carousel-item">
<div className="testimonial_content">
<a href={web1}>
<img
src={web1}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1 className="my-2">Pooja Dhayal</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "15px" }}
>
Dive to learn helped me to achieve my goals.I cleared UGC
NET exam in December ”
</ReactReadMoreReadLess>
</p>
</div>
</div>
<div className="carousel-item">
<div className="testimonial_content">
<a href={web2}>
<img
src={web2}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1 className="my-2">Parul</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "16px" }}
>
Hurreh!!!Finally, i got my JRF.Thank u so much Dive to
learn faculties.your video
”
</ReactReadMoreReadLess>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}

Solution
For your current implementation, only bullet point #1 of the explanation applies (see below). Therefore, the functional component should look like this:
import React from "react";
import web from "../../image/nisha.jpg";
import web1 from "../../image/Pooja.jpg";
import web2 from "../../image/6547.jpg";
import "../../styles.scss";
import ReactReadMoreReadLess from "react-read-more-read-less";
export default () => {
return (
<div>
<h1 className="blog_heading">Testimonials</h1>
<div className="testimonial">
<div
id="carouselExampleSlidesOnly"
className="carousel slide"
data-ride="carousel"
>
<div className="carousel-inner container">
<div className="carousel-item active">
<div className="testimonial_content">
<a href={web}>
<img
src={web}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1>Nisha Sinha</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "15px" }}
>
It's a big thanks for helping me a lot in achieving my
goal of JRF. All the lectues were so helpful and i really
learned from basic to the top and my doubts got cleared
whenever needed and really all the faculties helped with
quality videos ”
</ReactReadMoreReadLess>
</p>
</div>
</div>
<div className="carousel-item">
<div className="testimonial_content">
<a href={web1}>
<img
src={web1}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1 className="my-2">Pooja Dhayal</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "15px" }}
>
Dive to learn helped me to achieve my goals.I cleared UGC
NET exam in December ”
</ReactReadMoreReadLess>
</p>
</div>
</div>
<div className="carousel-item">
<div className="testimonial_content">
<a href={web2}>
<img
src={web2}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1 className="my-2">Parul</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "16px" }}
>
Hurreh!!!Finally, i got my JRF.Thank u so much Dive to
learn faculties.your video
”
</ReactReadMoreReadLess>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
Explanation
There are a few things to keep in mind when you want to swap from a class component to a functional component.
Change the header from a class header into a function header. You would need to change this:
export default class extends React.Component {
render() {
return (
// ...something
);
}
}
To this
export () => {
return (
// ...something
);
}
Update the usage of props if there's any. Assume that you use this.props somewhere in your component. You need to accept props as a parameter of your functional component and use that instead of this.props.
export (props) => {
console.log(`This is the props: ${props}`);
return (
// ...something
);
}
Use the useState hook instead of this.state and this.setState. Learn more
If you ever have to use the life cycle functions (componentDidMount,...), consider learning more about the useEffect hook. Learn more

A functional component is just a function that returns some jsx so the basic format of the function should look like this:
const Name = (props) => {
return (
<div>Your jsx</div>
)
}
I changed yours to a function real quick, not sure if this is all you needed? Were you having errors with the web componenets when you changed them?
import React from "react";
import web from "../../image/nisha.jpg";
import web1 from "../../image/Pooja.jpg";
import web2 from "../../image/6547.jpg";
import "../../styles.scss";
import ReactReadMoreReadLess from "react-read-more-read-less";
const newComp = props => {
return (
<div>
<h1 className="blog_heading">Testimonials</h1>
<div className="testimonial">
<div
id="carouselExampleSlidesOnly"
className="carousel slide"
data-ride="carousel"
>
<div className="carousel-inner container">
<div className="carousel-item active">
<div className="testimonial_content">
<a href={web}>
<img
src={web}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1>Nisha Sinha</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "15px" }}
>
It's a big thanks for helping me a lot in achieving my
goal of JRF. All the lectues were so helpful and i really
learned from basic to the top and my doubts got cleared
whenever needed and really all the faculties helped with
quality videos ”
</ReactReadMoreReadLess>
</p>
</div>
</div>
<div className="carousel-item">
<div className="testimonial_content">
<a href={web1}>
<img
src={web1}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1 className="my-2">Pooja Dhayal</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "15px" }}
>
Dive to learn helped me to achieve my goals.I cleared UGC
NET exam in December ”
</ReactReadMoreReadLess>
</p>
</div>
</div>
<div className="carousel-item">
<div className="testimonial_content">
<a href={web2}>
<img
src={web2}
alt="img"
className="rounded-circle img-fluid "
/>
</a>
<h1 className="my-2">Parul</h1>
<p>
<sup>
<i
className="fa fa-quote-left mr-2"
style={{ fontSize: "14px", color: "#ffca08" }}
aria-hidden="true"
></i>
</sup>
<ReactReadMoreReadLess
charLimit={200}
readMoreText={"Read more ▼"}
readLessText={"Read less ▲"}
readMoreStyle={{ color: "#00ba74", fontSize: "16px" }}
>
Hurreh!!!Finally, i got my JRF.Thank u so much Dive to
learn faculties.your video
”
</ReactReadMoreReadLess>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default newComp
<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>

Related

Semantic Ui Sidebar is not pushing content when it opens

Pusher is not pushing the content when sidebar opens up, instead it overlaps the content. Using the CDN of semantic ui and it seems that content inside pusher is not pushed.
function toggleMenu() {
setToogle(!toggle);
}
return (
<div>
<Header onToggleMenu={toggleMenu} />
<div className="ui attached pushable" style={{ height: "100vh", width: "175px" }} >
<Sidebarleft toggleMenu={toggle} />
<div className={` ui pusher ${(toggle) ? 'dimmed ' : ''}`} >
<div>Application Main Content</div>
</div>
</div>
Sidebarleft.js
<div class={`ui sidebar overlay push left inverted vertical menu animating ${(classes.visible) ? 'visible ' : ' '} `} >
<div style={{ marginTop: "25px", color: "GrayText", marginLeft: "15px", fontSize: "14px" }} >
MAIN
</div>
<div style={{ marginTop: "35px" }} >
<Link href="/SupplierOnboarding" className="item">
{/* <i class="home icon" style={{marginRight:"33px"}}></i> */}
<span>
{/* <i className="home icon"></i> */}
<i className="user icon" style={{marginLeft:"-5px",color:"white"}}></i>
</span>
<span style={{ marginLeft: "10px",color:"white" }}>Supplier Onboarding</span>
</Link>
</div>
</div>
Header.js
<div class="ui large vertically attached inverted menu">
<span className="item link grey" onClick={props.onToggleMenu}>
<i class="large bars icon "></i>
</span>
{/* <a class="item">
Services
</a>
<a class="item">
People
</a> */}
</div>

Map doesn't work after setState after fetch

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;```

Document query selector returns undefined in react

I am trying to build a toggle sidebar. when I click on the button the class list of .m-toggle should be updated. But react gives me an error
"TypeError: Cannot read property 'classList' of null"
Here is my code:
import React, { useState, useEffect } from 'react'
// import Sidebar from '../Components/Sidebar'
import AppleIcon from '#material-ui/icons/Apple'
import DashboardIcon from '#material-ui/icons/Dashboard'
import PeopleIcon from '#material-ui/icons/People'
import NotificationsIcon from '#material-ui/icons/Notifications'
import SettingsIcon from '#material-ui/icons/Settings'
import HelpIcon from '#material-ui/icons/Help'
import img from '../Assets/img/keval.jpg'
function toggleMenu() {
let toggle = document.querySelector('.m-toggle')
toggle.classList.toggle('m-active')
}
const Main = () => {
return (
<>
<div className="m-body">
<div className="m-container">
{/* -------Sidebar Start------- */}
<div className="m-navigation">
<ul style={{ padding: '0' }}>
<li>
<a href="#">
<span className="m-icon">
<AppleIcon className="muicon" />
</span>
<span className="m-title">
<h2>Brand Name</h2>
</span>
</a>
<hr style={{ color: 'white' }} />
</li>
<li>
<a href="#">
<span className="m-icon">
<DashboardIcon className="muicon" />
</span>
<span className="m-title">Dashboard</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<PeopleIcon className="muicon" />
</span>
<span className="m-title">Employees</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<NotificationsIcon className="muicon" />
</span>
<span className="m-title">Notification</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<HelpIcon className="muicon" />
</span>
<span className="m-title">Help</span>
</a>
</li>
<li>
<a href="#">
<span className="m-icon">
<SettingsIcon className="muicon" />
</span>
<span className="m-title">Setting</span>
</a>
</li>
</ul>
</div>
{/* --------Side BAr End--------- */}
<div className="m-main">
<div className="m-topbar">
<div className="m-toggle" onClick={toggleMenu()}>
f
</div>
<div className="m-search">
<label>
<input type="text" placeholder="Search here" />
</label>
</div>
<div className="user">
<img src={img} alt="no img" />
</div>
</div>
</div>
</div>
</div>
</>
)
}
export default Main
You can see the code where onclick class list should be updated but it is not updating.
One problem I see is that you are not passing a function reference in onClick, but doing a function call instead:
<div className="m-toggle" onClick={toggleMenu()}>
Either remove the parentheses after toggleMenu:
<div className="m-toggle" onClick={toggleMenu}>
or pass it as an inline arrow function:
<div className="m-toggle" onClick={() => toggleMenu()}>
Several problems:
React onClick expects a function but you are invoking toggleMenu instead. It should be onClick={toggleMenu} or onClick={()=>toggleMenu()}
You should be managing the className using state instead of using document.querySelector() and modifying the element yourself.
You are calling the toggleMenu() method during component render which you shouldn't do.
So when your component tries to render, it calls toggleMenu method and returns null for m-toggle query selector. you can either bind function reference or use arrow function.
<div className="m-toggle" onClick={toggleMenu}>
OR
<div className="m-toggle" onClick={() => toggleMenu()}>

How to add active class on div on link click inside of div

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.

dispatchConfig: {…}, _targetInst: FiberNode, _dispatchInstances ReactJS error

Hello ,
I was trying to code basket functions on react(onAdd func). But I encountered such a problem. Could you please tell me why? i have no idea about it .
You can see problem from here
I tried to add the add-to-cart function to my button, but I am facing such a problem, could you please tell me why?
import { Row, Col, Form, Button, Label, Input } from "reactstrap";
import Link from "next/link";
import items from "../data/products-cart.json";
import SelectBox from "./SelectBox";
import Stars from "./Stars";
import { useState } from "react";
export default function DetailMain({product}) {
const[CartItems,setCartItems]=useState(items);
console.log(CartItems);
const onAdd=(product)=>{
const exists=CartItems.find(x=>x.id === product.id);
if(exists){
setCartItems(
CartItems.map((x)=>
x.id===product.id ?{...exists,items: exists.items+1}:x
)
);
} else{
setCartItems([...CartItems,{...product,items:1}]);
}
};
console.log(product);
return (
<>
<h1 className="mb-4">{product.name}</h1>
<div className="d-flex flex-column flex-sm-row align-items-sm-center justify-content-sm-between mb-4">
<ul className="list-inline mb-2 mb-sm-0">
<li className="list-inline-item h4 font-weight-light mb-0">
${product.price.toFixed(2)}
</li>
<li className="list-inline-item text-muted font-weight-light">
<del>${product.priceBefore.toFixed(2)}</del>
</li>
</ul>
<div className="d-flex align-items-center">
<Stars
stars={4}
secondColor="gray-300"
starClass="mr-1"
className="mr-2"
/>
<span className="text-muted text-uppercase text-sm mt-1">
{product.reviewscount} reviews
</span>
</div>
</div>
<p className="mb-4 text-muted">{product.description.short}</p>
<Form>
<Row>
<Col sm="6" lg="12" xl="6" className="detail-option mb-4">
<h6 className="detail-option-heading">
Size <span>(required)</span>
</h6>
<SelectBox options={product.sizes} />
</Col>
<Col sm="6" lg="12" xl="6" className="detail-option mb-4">
<h6 className="detail-option-heading">
Type <span>(required)</span>
</h6>
{product.types.map((type) => (
<Label
key={type.value}
className="btn btn-sm btn-outline-secondary detail-option-btn-label mr-2"
tag="label"
for={type.id}
>
{" "}
{type.label}
<Input
className="input-invisible"
type="radio"
name="material"
value={type.value}
id={type.id}
required
/>
</Label>
))}
</Col>
<Col xs="12" lg="6" className="detail-option mb-5">
<label className="detail-option-heading font-weight-bold">
Items <span>(required)</span>
</label>
<input
className="form-control detail-quantity"
name="items"
type="number"
defaultValue={1}
/>
</Col>
</Row>
<ul className="list-inline mb-5">
<li className="list-inline-item">
<Button onClick={onAdd} color="dark" size="lg" className="mb-1" type="submit">
<i className="fa fa-shopping-cart mr-2" />
Add to Cart
</Button>
</li>
<li className="list-inline-item">
<Button color="outline-secondary" className="mb-1" href="#">
<i className="far fa-heart mr-2" />
Add to wishlist
</Button>
</li>
</ul>
<ul className="list-unstyled">
<li>
<strong>Category: </strong>
<a className="text-muted" href="#">
{product.category}
</a>
</li>
<li>
<strong>Tags: </strong>
{product.tags.map((tag, index) => (
<React.Fragment key={tag.name}>
<Link href={tag.link}>
<a className="text-muted">{tag.name}</a>
</Link>
{index < product.tags.length - 1 ? ",\u00A0" : ""}
</React.Fragment>
))}
</li>
</ul>
</Form>
</>
);
}
Your data should be in the same format as the data you rendered before.

Categories