Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!