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

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.

Related

How to align elements in footer correctly

How do i center/align these columns correctly. Im using React with the React-Bootstrap lib.
This is my js for the footer component.
<kbd>import { Container, ListGroup } from "react-bootstrap";
const ContainedFooterElement= () => {
return (
<Container>
<footer className="footer mt-auto py-3 bg-dark text-white">
<div className="footer-content">
<ListGroup className="row px-5 list-unstyled">
<h4>Social's</h4>
<li>Facebook Icon</li>
<li>Instagram Icon</li>
<li>Twitter Icon</li>
<li>Any Icon etc</li>
<h4>Flowers4Sale.com</h4>
<li>Our Selection</li>
<li>View Other Locations</li>
<li>Twitter Icon</li>
<li>Any Icon etc</li>
<h4>Community</h4>
<li>Forum</li>
<li>Email Us</li>
</ListGroup>
<br />
</div>
<div className="footer-bottom">
<p className="text-xs-center mx-auto px-5 ">
©{new Date().getFullYear()} Portland: Flowers4Sale-All Rights Reserved.
</p>
</div>
</footer>
</Container>
);
}
export default ContainedFooterElement;
Any help is much appreciated. this just stumps me right now.
I tried putting my li tags in and now I'm stumped. I tried making each li a <ListGroup.Item> but that didn't work for me.
you can add text-center like this:
<ListGroup className="row px-5 list-unstyled text-center">
....
</ListGroup>
<p className="text-center mx-auto px-5 ">
....
</p>

Close the mobile menu by clicking or tapping outside

The code is for mobile menu but when I open it, it stays open and won't close.
I want it to close by clicking the menu links and tapping outside.
I know I haven't even added in the code but I don't know how to add into it.
Can anyone help me with the code? Any help is appreciated!
Here is the code :
import { useState } from "react";
import { HiMenuAlt3, HiX } from "react-icons/hi";
export default function NavBar() {
const [navbar, setNavbar] = useState(false);
return (
<nav className="w-full bg-white shadow">
<div className="justify-between px-4 mx-auto lg:max-w-7xl md:items-center md:flex md:px-8">
<div>
<div className="flex items-center justify-between py-3 md:py-5 md:block">
<a href="javascript:void(0)">
<h2 className="text-2xl font-bold">LOGO</h2>
</a>
<div className="md:hidden">
<button
className="p-2 text-gray-700 rounded-md outline-none focus:border-gray-400 focus:border"
onClick={() => setNavbar(!navbar)}
>
{navbar ? (
<HiX className="text-4xl" /> // Close icon
) : (
<HiMenuAlt3 className="text-4xl" /> // Open icon
)}
</button>
</div>
</div>
</div>
<div>
<div
className={`flex-1 justify-self-center pb-3 mt-8 md:block md:pb-0 md:mt-0 ${
navbar ? "block" : "hidden"
}`}
>
<ul className="items-center justify-center space-y-8 md:flex md:space-x-6 md:space-y-0">
<li className="text-gray-600 hover:text-blue-600">
Home
</li>
<li className="text-gray-600 hover:text-blue-600">
Blog
</li>
<li className="text-gray-600 hover:text-blue-600">
About US
</li>
<li className="text-gray-600 hover:text-blue-600">
Contact US
</li>
</ul>
</div>
</div>
</div>
</nav>
);
}
You do have code to close it, setNavbar(false). What you need is a hooked called useOnClickOutside. https://usehooks.com/useOnClickOutside/
To use it,
function NavBar() {
const ref = useRef()
useOnClickOutside(ref, () => setNavbar(false));
return (
<nav ref={ref}>
...
</nav>
)
}

Toggle Button JavaScript Code Not Working in React JS

I just want to ask help with the comment section down below of the JavaScript Code. I want to work the toggle button / hamburger button but it does not work because addEventListener is not required for ReactJS. What code must be encoded? Thank you.
I am doing a Traversy Media Tutorial using Tailwind CSS. I want to use React as framework because of its composable component feature and efficiency to use.
import React from 'react';
import logo from '../images/logo.svg';
// const btn = document.getElementById('menu-btn')
// const nav = document.getElementById('menu')
// btn.addEventListener('click', () => {
// btn.classList.toggle('open')
// nav.classList.toggle('flex')
// nav.classList.toggle('hidden')
// })
const Navbar = () => {
return (
<div>
<nav className='relative container mx-auto p-6'>
{/* Flex Container */}
<div className='flex items-center justify-between'>
{/* Logo */}
<div className='pt-2'>
<img src={logo} alt='logo.svg'></img>
</div>
{/* Menu Items */}
<div className='hidden space-x-6 md:flex'>
<a href='/' className='hover:text-darkGrayishBlue'>
Pricing
</a>
<a href='/' className='hover:text-darkGrayishBlue'>
Product
</a>
<a href='/' className='hover:text-darkGrayishBlue'>
About Us
</a>
<a href='/' className='hover:text-darkGrayishBlue'>
Careers
</a>
<a href='/' className='hover:text-darkGrayishBlue'>
Community
</a>
</div>
{/* Button */}
<div>
<a
href='/'
className='hidden p-3 px-6 pt-2 text-white bg-brightRed rounded-full baseline hover:bg-brightRedLight md:block'
>
Get Started
</a>
</div>
{/* Hambuger Icon */}
<button
id='menu-btn'
className='block hamburger md:hidden focus:outline-none'
>
<span className='hamburger-top'></span>
<span className='hamburger-middle'></span>
<span className='hamburger-bottom'></span>
</button>
</div>
{/* Mobile Menu */}
<div className='md:hidden'>
<div
id='menu'
className='absolute flex-col items-center hidden self-end py-8 mt-10 space-y-6 font-bold bg-white sm:w-auto sm:self-center left-6 right-6 drop-shadow-md'
>
<a href='/'>Pricing</a>
<a href='/'>Product</a>
<a href='/'>About</a>
<a href='/'>Careers</a>
<a href='/'>Community</a>
</div>
</div>
</nav>
</div>
);
};
export default Navbar;
What you could do is define an open state and a click listener for the button.
Then change the class of the objects based on the open flag:
import React from 'react';
import logo from '../images/logo.svg';
const Navbar = () => {
const [open, setOpen] = useState(false);
const handleMenuClick = () => {
setOpen((prev) => !prev);
};
return (
<div>
<nav className='relative container mx-auto p-6'>
{/* Flex Container */}
<div className='flex items-center justify-between'>
{/* ... */}
{/* Hambuger Icon */}
<button
id='menu-btn'
className={`block hamburger md:hidden focus:outline-none ${
open && 'open'
}`}
onClick={() => handleMenuClick()}
>
<span className='hamburger-top'></span>
<span className='hamburger-middle'></span>
<span className='hamburger-bottom'></span>
</button>
</div>
{/* Mobile Menu */}
<div className='md:hidden'>
<div
id='menu'
className={`absolute flex-col items-center hidden self-end py-8 mt-10 space-y-6 font-bold bg-white sm:w-auto sm:self-center left-6 right-6 drop-shadow-md ${
open ? 'flex' : 'hidden'
}`}
>
<a href='/'>Pricing</a>
<a href='/'>Product</a>
<a href='/'>About</a>
<a href='/'>Careers</a>
<a href='/'>Community</a>
</div>
</div>
</nav>
</div>
);
};
export default Navbar;
```
You need to define the event handling where you define your button. In your case, it would look something like this:
<button
id='menu-btn'
className='block hamburger md:hidden focus:outline-none'
onClick={doAction}>
>
Official documentation regarding event handling in react.

Uncaught TypeError: state.productDetails is not a function

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. :)

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

Categories