Bashd
Bashd

Reputation: 11

How to switch radio buttons from true back to false in ReactJS

Ok, so I am able to turn the Radio Buttons from false to true, but I can't figure out a way to turn the radio buttons back to false when you uncheck them. I was wondering if anyone could help me.

const [long, setLong] = useState(false);
       
const handleSubmit = (e) => {
     e.preventDefault();
     console.log({name, long, short, both, entry, exit})
        };
    
<input type="radio" value='isLong' name='long' onCheck={(e) => setLong(!long)}/>isLong?

Upvotes: 1

Views: 45

Answers (2)

Emanuele Scarabattoli
Emanuele Scarabattoli

Reputation: 4469

You should use an input of type checkbox for this specific problem

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Use checked prop

<input type="radio" value='isLong' name='long' checked={long} onChange={(e) => setLong(!long)}/>isLong?

Also long and short are reserved words. Consider using different names.

And if the next state depends on the current state consider using callback form of setState calls

onChange={() => setLong(isLong => !isLong)}

Upvotes: 1

Related Questions