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

3.1K
Visualizações
How to add or remove a className on event in ReactJS?

I am quite new to React and I am struggling a little with converting my thinking from standard js.

In my react component I have the following element:

<div className='base-state' onClick={this.handleClick}>click here</div>

The behaviour I am looking for is to add an extra class on click. My first idea was to try and add the class in the click handler function e.g.

handleClick : function(e) {
   <add class "click-state" here>
}

I haven't been able to find any examples that do anything similar though, so I am fairly sure I am not thinking about this in the right way.

Can anyone point me in the right direction?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The list of classes can be derive from the state of the component. For example:

var Component = React.createClass({
  getInitialState: function() {
    return {
      clicked: false
    };
  },

  handleClick: function() {
    this.setState({clicked: true});
  },

  render: function() {
    var className = this.state.clicked ? 'click-state' : 'base-state';
    return <div className={className} onClick={this.handleClick}>click here</div>;
  }
});

Calling this.setState will trigger a rerender of the component.

over 4 years ago · Santiago Trujillo Relatório

0

You could use just a Vanilla JS (event.target and classList):

handleClick = event => event.target.classList.add('click-state');

render() {
  return <div className="base-state" onClick={this.handleClick}>Click here</div>;
}

BUT don't do that!

React should handle changes in the DOM, so rely on modifying CSS classes via React.

Event.target

Element.classList

React / Styling and CSS

over 4 years ago · Santiago Trujillo Relatório

0

You could set click state in the click handler function and use it to set the class name conditionally using a template literal.

If you're using a function component, you can do it this way using the useState hook:

const [clicked, setClicked] = useState(false);

<div className={ `base-state ${clicked && 'click-state'}` } onClick={ () => setClicked(true) }>click here</div>
over 4 years ago · Santiago Trujillo 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