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
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
you should use setIsTrue(!isTrue)