Home > front end >  Highlight clicked button with React/Tailwind
Highlight clicked button with React/Tailwind

Time:11-21

I want to change the appearence of an button after clicking it. I have tried adding focus: / active:, but react is re-rendering the component on-click, so it doesn't work.

In Javascript I would add an event-handler to every button that would automatically change the appearence after being clicked, how am I able to recreate that in react/tailwind-css, since tailwind is not working with dynamic className changes?

Is there a good practice, or should I add if statements in order to make it work?

This is what I am trying to recreate.

HTML:
<button>MY BUTTON</button>
<button>MY BUTTON</button>
<button>MY BUTTON</button>
JS:
let button_list = document.querySelectorAll("button");
button_list.forEach(element=>{
  element.addEventListener("click",function(){
    button_list.forEach(remove_background=>{
      remove_background.style.background="white";
    });
    this.style.background="black";
  });
});

CodePudding user response:

I would recommend a state variable to store the active button. Here's a simple example:

const ButtonList = () => {
  const [activeButtonIndex, setActiveButtonIndex] = useState(0);
  return (
    <>
      <button
        className={activeButtonIndex === 0 ? "bg-white" : "bg-black"}
        onClick={() => setActiveButtonIndex(0)}
      >
        My Button
      </button>
      <button
        className={activeButtonIndex === 1 ? "bg-white" : "bg-black"}
        onClick={() => setActiveButtonIndex(1)}
      >
        My Button
      </button>
      <button
        className={activeButtonIndex === 2 ? "bg-white" : "bg-black"}
        onClick={() => setActiveButtonIndex(2)}
      >
        My Button
      </button>
    </>
  );
};
  • Related