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

184
Visualizações
React conditional update setState on basis of previous values, if state value is true make it false and vice versa

I have a state

const [textColor, setTextColor] = useState({
  darkText: false,
  lightText: false,
  allTextSelected: false,
})

Now I want to update this state conditionally, if darkText is true make it false and vice versa

Using ternary operator and callback

  const onClickDarkText = () => {
    setTextColor((prevState) => (
    prevState.darkText ? { ...prevState, darkText: false } : { ...prevState, darkText: true }
  ))
 }

Left-hand side doesn't work

Using if/else

  const onClickDarkText = () => {
    if (textColor.darkText) {
     setTextColor({
      darkText: false,
      lightText: false,
      allTextSelected: false,
    })
   setEmptyFilter(true)
  }
  else {
    setTextColor({
      darkText: true,
      lightText: false,
      allTextSelected: false,
    })
     setEmptyFilter(false)
 }
}

darkText doesn't get back to false once it becomes true

I would be glad if you help me to find out whats wrong.

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

0

You can toggle the state for the darkText. Please refer to the code:

import React, { useState } from 'react';

export default function App() {
  const [textColor, setTextColor] = useState({
    darkText: false,
    lightText: false,
    allTextSelected: false,
  });
  const handleClick = () => {
    setTextColor((prevState) => {
      return { ...prevState, darkText: !prevState.darkText };
    });
  };
  console.log('textColor.darkText', textColor.darkText);
  return (
    <div>
      {textColor.darkText ? <div>textColor is true</div> : null}
      <button onClick={handleClick}>Click</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need if else, you can toggle it like this:

const onClickDarkText = () => {
    // ...textColor will spread all the current values on the new value
    // toggle darkText with its new value using !
    setTextColor({ ...textColor, darkText : !textColor.darkText})
 }
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