Home > Software engineering >  Add active class by default to the first element from class list and change active class on click re
Add active class by default to the first element from class list and change active class on click re

Time:07-16

I'm a newbie in react. I have two class in css file. One is btn and another is btn-active. I want to set an btn-active class to the first button by default and when I click on other buttons it'll be remove and add to the current button. I'll be thankful if anyone help me about this. Thanks in advance.

import { useState } from "react";
import buttons from "../data/buttons.json";

const Home = () => {
  return (
    <div>
      {buttons.map((item, index) => {
        return (
          <button key={index} className="btn">
            {item.valu}
          </button>
        );
      })}
    </div>
  );
};

CodePudding user response:

Keep a state to handle the selected button index.

Try like below:

import { useState } from "react";

const Home = () => {
  const [selectedIndex, setSelectedIndex] = useState(0);

  return (
    <div>
      {buttons.map((item, index) => {
        return (
          <button
            key={index}
            onClick={() => setSelectedIndex(index)}
            className={`btn ${selectedIndex === index ? "active" : ""}`}
          >
            {item.valu}
          </button>
        );
      })}
    </div>
  );
};
  • Related