0

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;
2
  • Your button group seems to have the same functionality as a radio button group, have you considered styling a radio button group to look like buttons? Commented Apr 30, 2021 at 0:18
  • this can be done in a lot of ways so not going there, the problem with the code above is that you are trying to control the state of 5 different things with one variable, so if any one button does it, everyone shares the same value. Commented Apr 30, 2021 at 0:18

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

8 Comments

Can also use index in case an id is not available.
@Cybershadow OP used btn.id in their code already so I assumed it was fair game.
Ah good observation, I didn't catch that id parameter at first glance.
@Nick Tysm! That worked like a charm. Would this work if I do onClick={handleClick} on <button>? and have a function outside const handleClick = (e) => {e.preventDefault(); setActive(btn.id); ?
@KenRyan yes! You should be able to use setActive(e.target.id) to get the button's ID
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.