user9258981
user9258981

Reputation: 155

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.

Upvotes: 0

Views: 1523

Answers (2)

I am L
I am L

Reputation: 4632

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

Upvotes: 1

Erick
Erick

Reputation: 1146

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

Upvotes: 1

Related Questions