I want to show the content on the cards (marked in red and named product.description in the code) on click but I don't know any way of doing it.
The content on the card is fetched from JSON-server.
Here is some code
The first js is used to fetch the data from the server and display that on the page and the second one is the method of showing the data on the page. In general, I want the p tag to appear and disappear when the user clicks on the main div named
Product-Preview
import { useEffect, useState } from "react";
import ProductList from "./ProductList";
const Products = () => {
const [products, setProducts] = useState (null);
useEffect (() => {
fetch('http://localhost:8000/products')
.then(res => {
return res.json();
})
.then(data => {
setProducts(data);
})
}, []);
return (
<div className="ProductList">
{products && <ProductList products={products}/>}
</div>
);
}
export default Products;
const ProductList = (props) => {
const products = props.products;
return (
<div className="ProductList" >
{products.map((product) => (
<div className="Product-Preview" key={product.id}>
<div className="backdrop" style={{backgroundImage: `url(${product.image})`}}></div>
<h2>{ product.title }</h2>
<p>{ product.description }</p>
<div>{ product.price }</div><br />
</div>
))}
</div>
);
}
export default ProductList;
You should create a component and use a state in this component to do it.
Example component has a name is Card
const Card= ({ product }) => {
const [showDescription, setShowDescription] = useState(false);
return (
<div
className="Product-Preview"
onClick={() => setShowDescription(!showDescription)}
>
<div className="backdrop" style={{ backgroundImage: `url(${product.image})` }}></div>
<h2>{product.title}</h2>
{showDescription && <p>{product.description}</p>}
<div>{product.price}</div>
<br />
</div>
);
};
And use this component inside map
{
products.map((product) => <Card product={product} key={product.id} />);
}