I am using an array of objects to loop some services in my webpage. The data is
data.js
const data = [
{ type: "Mirror Cleaning", price: "29" },
{ type: "Ceiling Fan Cleaning", price: "39" },
{ type: "Window Cleaning", price: "139" },
{ type: "Toilet Seat Stain Removal", price: "109" },
{ type: "Wash Basin Cleaning", price: "49" },
{ type: "Exhaust Fan Cleaning", price: "79" },
{ type: "Kitchen Sink Cleaning", price: "79" },
{ type: "Gas Stove (HOB) Cleaning", price: "89" },
];
export default data;
I added a button in my app.js where I can select and unselect the data which I added to the service array. But the problem is whenever I select a service in my app all button name changed from Select to Unselect which I don't want. I want to achieve only the item that I clicked its button changed. But all the buttons in the window change. I know where is the problem but I don't know how to achieve what I want to. Here is the code of my app.js.
App.js
import "./styles.css";
import React from "react";
import data from "./data";
export default function App() {
const [service, setService] = React.useState([]);
const [display, setDisplay] = React.useState(true);
function Select(type, price) {
setService((prevItems) => [...prevItems, { type: type, price: price }]);
setDisplay(false);
}
function Unselect(type, price) {
setService((prevItems) => prevItems.filter((data) => data.type !== type));
setDisplay(true);
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{data.map((data) => (
<>
<div key={data.type} style={{ height: "80px" }}>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between"
}}
>
<div>{data.type}</div>
<div>{data.price}</div>
</div>
{display ? (
<button
onClick={() => Select(data.type, data.price)}
style={{
color: "white",
backgroundColor: "black",
padding: "10px",
outline: "0",
border: "none",
margin: "0px auto 0px 0px"
}}
>
Select
</button>
) : (
<button
onClick={() => Unselect(data.type, data.price)}
style={{
color: "white",
backgroundColor: "black",
padding: "10px",
outline: "0",
border: "none",
margin: "0px auto 0px 0px"
}}
>
Unselect
</button>
)}
</div>
</>
))}
<p> Selected Services comes here </p>
{service.map((data) => (
<>
<div
key={data.type}
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
height: "50px"
}}
>
<div>{data.type}</div>
<div>{data.price}</div>
</div>
</>
))}
</div>
);
}
Here is the link of the codesandbox that I checked the code.
I want that only the particular service that is clicked its button change from select to unselect but all of them are changing. please help.