I'm trying to figure how to update the a single element in a react .map. I want to add a selected state to my react button but right now its adding the selected state to all my buttons. I'm not sure how to go about this and wondering if someone could help me out please.
I've put to together a codeandsandbox to demonstrate what is happening, I'm trying to do this in the Dashboard.jsx page in the handleButtonClick function, I know it will need to take in an id but at this point I'm not sure what else.
import React, { useEffect, useState } from 'react';
import PropTypes from "prop-types";
import Item from './Item';
import { fetchData } from '../api/fetcher';
const Dashboard = () => {
const [response, setResponse] = useState([]);
const [isSelected, setIsSelected] = useState(false);
//call data on page load
useEffect(() => {
fetchData(setResponse);
}, [])
console.log(response);
const handleButtonClick = (id) => {
setIsSelected(!isSelected)
}
return (
<React.Fragment>
{response.map(items =>
<Item
prodId={items.productId}
key={items.productId}
image={items.imageUrl}
description={items.description}
itemName={items.name}
discount={items.promotionBadge}
price={items.price}
priceWas={items.priceWas}
selected={isSelected}
onClick={() => handleButtonClick(items.productId)}
/>
)}
</React.Fragment>
);
}
export default Dashboard;
the setIsSelected(!isSelected) applies the style to all the buttons.
Here is my code and how it works:
https://codesandbox.io/s/charming-butterfly-vy6v8?file=/src/App.js