Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add active class by default to the first element from class list and change active class on click react

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>
  );
};
like image 285
Mahabub Hossain Avatar asked Nov 01 '25 11:11

Mahabub Hossain


1 Answers

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>
  );
};
like image 86
Amila Senadheera Avatar answered Nov 04 '25 21:11

Amila Senadheera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!