i am creating a react app, in that i have created a button component.
Button Component :
import React, { useState } from "react";
export default function Button(props){
const [categoryButton, setCategoryButton] = useState(false);
function categoryButtonClick (){
setCategoryButton(true);
}
return <button
className="button"
style={{backgroundColor:categoryButton?"#FD5D5D":"white"}}
onClick={categoryButtonClick}>{props.name}</button>
}
Category Component :
import React from "react";
import Button from "./Button";
const categoryArray = [
{
id:1,
category:"Starter"
},
{
id:2,
category:"Cold Beverages"
},
{
id:3,
category:"Hot Beverages"
},
{
id:4,
category:"South Indian"
},
{
id:5,
category:"Starter"
},
{
id:6,
category:"Cold Beverages"
},
{
id:7,
category:"Hot Beverages"
},
{
id:8,
category:"South Indian"
},
{
id:9,
category:"Italian"
}
]
export default function Category(){
return (
<div className="category-tray">
{categoryArray.map((categoryTerm) => (
<Button key={categoryTerm.id} name={categoryTerm.category} />
))}
</div>
);
}
when a user click on a button (from 12 button available) the background color change to #FD5D5D from white.
now i want that when ever user click on another button the previous button (that got clicked earlier) get the white color back.
i tried using reset function but nothing happen`
3
Answers
I would use
context
to handle a global state that determines which button was pressed and change its color.You have to handle the click event directly on the parent component if you want each child (button component) to know the state (clicked or not) of the other.
Your parent component :
Your child component :
I suggest that you move your state to the Category component and pass the active state to the Button component. To gain a better understanding, you may review the code I have written. I hope this will be helpful.