I have a list of buttons. I want to make one of them to have a active state and when that one has every other shouldn't have that state. So styling is applied only to the active one. I almost did it, i mean it change styling when i press on each other but i have no idea how to make it to deactivate a button when i click on another one.
Bellow is my code. props.planets is array of object {id: 'name', title: 'name'}
MenuList it takes a props.planets and generate list of MenuButton components
const MenuList = (props) => {
return (
<ul className={classes.planet_list}>
{props.planets.map((planet) => (
<MenuButton key={planet.id} title={planet.title} />
))}
</ul>
);
};
MenuButton is my button component i want it to have module classes: modulebutton as a main styling, class based on title, and an active class if button is active
const MenuButton = (props) => {
const [active, setActive] = useState();
const clickHandler = () => {
setActive({ active: props.title });
};
return (
<li>
<div
className={`${classes.menubutton} ${classes[props.title]} ${
active && classes.active
}`}
onClick={clickHandler}
>
{props.title}
</div>
</li>
);
};
CodePudding user response:
You need to have the active state in the parent not in the child component
MenuList.js
const MenuList = (props) => {
const [active, setActive] = useState();
function activeButton(value){
setActive(value)
}
return (
<ul className={classes.planet_list}>
{props.planets.map((planet) => (
<MenuButton onChange={activeButton} disabled={active} key={planet.id} title={planet.title} />
))}
</ul>
);
};
MenuButton.js
const MenuButton = (props) => {
const clickHandler = (keyID) => {
props.onChange(keyID)
};
return (
<li>
<div
className={props.active === props.key ? "activeClass" : "inactiveClass"}
onClick={() => clickHandler(props.key)}
>
{props.title}
</div>
</li>
);
};
That should be it. May need a useEffect but let me know of any bugs
