Home > OS >  React conditional update setState on basis of previous values, if state value is true make it false
React conditional update setState on basis of previous values, if state value is true make it false

Time:02-02

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.

CodePudding user response:

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>
  );
}

CodePudding user response:

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})
 }
  •  Tags:  
  • Related