I need to be able to click on the black or red dot color options and display the product in that color. I have both jackets saved in MongoDB.
Here's the code for the Product Component:
const Product = () => {
const location = useLocation();
const id = location.pathname.split("/")[2];
const [product, setProduct] = useState({});
const [quantity, setQuantity] = useState(1);
const [color, setColor] = useState("");
const [size, setSize] = useState("");
const dispatch = useDispatch();
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/products/find/" + id);
setProduct(res.data);
} catch {}
};
getProduct();
}, [id]);
const handleQuantity = (type) => {
if (type === "dec") {
quantity > 1 && setQuantity(quantity - 1);
} else {
setQuantity(quantity + 1);
}
};
const handleClick = () => {
dispatch(addProduct({ ...product, quantity, color, size }));
};
return (
<Container>
<Navbar />
<Announcement />
<Wrapper>
<ImgContainer>
<Image src={product.img} />
</ImgContainer>
<InfoContainer>
<Title>{product.title}</Title>
<Desc>{product.desc}</Desc>
<Price>$ {product.price}</Price>
<FilterContainer>
<Filter>
<FilterTitle>Color</FilterTitle>
{product.color?.map((c) => (
<FilterColor color={c} key={c} onClick={() => setColor(c)} />
))}
</Filter>
<Filter>
<FilterTitle>Size</FilterTitle>
<FilterSize onChange={(e) => setSize(e.target.value)}>
{product.size?.map((s) => (
<FilterSizeOption key={s}>{s}</FilterSizeOption>
))}
</FilterSize>
</Filter>
</FilterContainer>
<AddContainer>
<AmountContainer>
<Remove
style={{ cursor: "pointer" }}
onClick={() => handleQuantity("dec")}
/>
<Amount>{quantity}</Amount>
<Add
style={{ cursor: "pointer" }}
onClick={() => handleQuantity("inc")}
/>
</AmountContainer>
<Button onClick={handleClick}>ADD TO CART</Button>
</AddContainer>
</InfoContainer>
</Wrapper>
<Newsletter />
<Footer />
</Container>
);
};
export default Product;
Here's the item in MongoDB:
Here's the code for the model:
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema(
{
title: { type: String, required: true, unique: true },
desc: { type: String, required: true },
img: { type: Array },
categories: { type: Array },
size: { type: Array },
color: { type: Array },
price: { type: Number, required: true },
inStock: { type: Boolean, default: true },
},
{ timestamps: true }
);
module.exports = mongoose.model("Product", ProductSchema);
I feel like I should create a useState setImg function in addition to the setColor(c) in the onClick that would map through the available images in the db (the black jacket and the red jacket), and somehow display the correct colored jacket based on which colored dot I click on before a user can add what they want to the cart. Any help would be greatly appreciated!