简体   繁体   中英

ReactJs adding 'active' class to a button in a list of buttons

I have a list of buttons created dynamically with the.map function. I am trying to add an "active" class to the button onClick and get rid of the "active" class of the other buttons.

This is what I have so far. The issue is that it's adding the class but not getting rid of the class on the other buttons. Any help is appreciated: Thank you :)

const Buttons = (props) => {
  const [active, setActive] = useState(false);
  const handleClick = (event) => {
    event.preventDefault();
    setActive(true)
  }
    const buttons = props.buttons.map((btn,index) => {
        return(
        
      <button className={active === true ? 'active' : ''} id={btn.id} onClick={handleClick}>{btn.name}</button>
        )
    })
    return (
        <div>
         {buttons}
        </div>
    )
}
export default Buttons;

Since you need to know which button is active, it would be better to store the id of the active button in state rather than just a boolean. That way, you can know exactly which one as you map over them should be active.

const Buttons = (props) => {
  const [active, setActive] = useState();

  const handleClick = (event) => {
    event.preventDefault();
    setActive(event.target.id);
  }

  const buttons = props.buttons.map((btn, index) => {
    return (
      <button
        key={btn.id}
        className={active === btn.id ? "active" : undefined}
        id={btn.id}
        onClick={handleClick}
      >
        {btn.name}
      </button>
    );
  });
  return <div>{buttons}</div>;
};

export default Buttons;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM