Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
In React, how to add class to button when click

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>
  );
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>
about 4 years ago · Juan Pablo Isaza Relatório

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can extract your button-props to a function if the markup gets a bit longwinded

export default function App() {
  const [chosen, choose] = React.useState();

  const makeProps = (name) => ({
    onClick: () => choose(name),
    className: chosen === name ? 'active' : null
  })

  return (
    <div className="App">
      <button {...makeProps('one')}>one</button>
      <button {...makeProps('two')}>two</button>
      <button {...makeProps('duck')}>duck</button>
    </div>
  );
}

Or encapsulate the entire behaviour to its own 'ButtonThatCanBeActive' component that takes a "active" and "onClick" prop

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda