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

81
Visualizações
how to setstate in handleclick in reactjs

im a beginner concerning react .i do not know why setState in the handleclick function doesn't work properly . this is the code


class Toggle extends React.Component {
    constructor(props) {
        super(props);
        this.state = { isDark: false }
    }
    handleOnClick = () => {
        this.setState(prevState => ({ isDark: !prevState.isDark }))
        if (this.state.isDark === 'true') {
            setTheme('theme-dark')
        }
        else setTheme('theme-light')
    }
render() {

        return (
            <button onClick={this.handleOnClick}>
          </button>

so when i click the button the state of isDark will always be false , that means setState is not working i guess

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

the problem is that the react lifecycle will update the state after the sync function handleOnClick complete. You may try this way:

handleOnClick = () => {
  this.setState(prevState => {
    const isDark = !prevState.isDark;
    if (isDark === true) {
      setTheme('theme-dark');
    } else setTheme('theme-light');
    return {...prevState, isDark};
  })
};

or using lifecycle method https://reactjs.org/docs/react-component.html#componentdidupdate

componentDidUpdate(){
 if (this.state.isDark === true) {
   setTheme('theme-dark');
 } else setTheme('theme-light');
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to write this

this.handleOnClick = this.handleOnClick.bind(this);

at the end of your constructor and in handleOnClick function create local variable to save new value:

handleOnClick = () => {
    const isDark = !this.state.isDark;

    this.setState({ isDark: isDark });

    if (isDark === true) {
        setTheme('theme-dark')
    } else {
        setTheme('theme-light');
    }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

the code is correct but in the conditional statement there is a huge mistake i was comparing this.state.isDark ==='true'

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