Home > database >  In React, how to add class to button when click
In React, how to add class to button when click

Time:11-02

I am newbie in Reactjs. How to add class to button when clicked ? Also other buttons class should be removed

This is what I tried so far. Please help.

import React, { useState } from "react";
 
export default function App() {
  const [isActive, setActive] = useState("false"); 
  const handleToggle = () => {
    setActive(!isActive);
  };
  return (
    <div > 
      <button onClick={handleToggle}  className={isActive ? "active" : null}>Sunday</button>
      <button onClick={handleToggle} className={isActive ? "active" : null}>Monday</button> 
      <button onClick={handleToggle} className={isActive ? "active" : null}>Tuesday</button> 
      <button onClick={handleToggle} className={isActive ? "active" : null}>Wedsday</button> 
      <button onClick={handleToggle} className={isActive ? "active" : null}>Thursday</button> 
      <button onClick={handleToggle} className={isActive ? "active" : null}>Friday</button> 
      <button onClick={handleToggle} className={isActive ? "active" : null}>Saturday</button> 
    </div>
  );
}

CodePudding user response:

Assuming you have a src/index.css file that contains the required css class... your current script will assign the "active" class to all buttons at once. To apply the class to a single button you need to have an object in state like so:

const [daysActive, setDaysActive] = useState({ monday: false, tuesday: false... });

and in your toggle method you will pass the day key as such:

const handleToggle = (day) => {
  setDaysActive({
    ...daysActive,
    [day]: !daysActive[day]
  });
}

so a jsx button will call this handler with its respective day key

<button onClick={() => handleToggle("sunday")} className={daysActive["sunday"] ? "active" : null}>Sunday</button>

if you'd like to make this button set cleaner you can use the map function

const days = ["sunday", "monday", ...];

<div>
  {days.map((day) => (
    <button ... />
  ))}
</div>

CodePudding user response:

One way to do this is to use array map with index like this:

import React, { useState } from "react";
 
export default function App() {
  const days = ['Monday', 'Tuesday', ... ]
  const [activeIndex, setActiveIndex] = useState(-1); 
  const handleToggle = (index) => {
    setActiveIndex(index);
  };
  return (
    <div > 
{days.map((day, index) => (
      <button onClick={()=> handleToggle(index)}  className={activeIndex === index ? "active" : null}>{day}</button> 
)
    </div>
  );
}
  • Related