skip to Main Content

I have a simple true/false switching function:

import {useState} from 'react'
const [ isTrue, setIsTrue] = useState(true)

function handleSwitcher(){
    {isTrue ? setIsTrue(false) : setIsTrue(true)}
}

<button onClick={()=>{
    handleSwitcher()
    console.log(isTrue)
}}>
   Set to true
</button>

<button onClick={()=>{
    handleSwitcher()
    console.log(isTrue)
}}>
   Set to false
</button>

If we click on both of buttons it will always render opposite to true or false. What I need is, if isTrue’s value is false and I click on ‘Set to false’ button it doesn’t change isTrue’s value to true. Same to ‘Set to true’ button, it shouldn’t change isTrue’s value to false, when value is true.

2

Answers


  1. You don’t need a handleSwitcher, just set the desired value when you click on the button, then it will be exactly the way you want

    import {useState} from 'react'
    const [ isTrue, setIsTrue] = useState(true)
    
    <button onClick={()=>{
        setIsTrue(true)
        console.log(isTrue)
    }}>
       Set to true
    </button>
    
    <button onClick={()=>{
        setIsTrue(false)
        console.log(isTrue)
    }}>
       Set to false
    </button>
    
    Login or Signup to reply.
  2. you should use setIsTrue(!isTrue)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search