AnswerBun.com

Unable to change checkbox in react hooks

Stack Overflow Asked by Nesh on January 3, 2022

I started learning React hooks, but I am stuck with a basic behavior of checkbox. I simply want to toggle my checkbox on click / change. Let me know what I am doing wrong here.

Code –

import React from "react";
import "./styles.css";

export default function App() {
  const [checked, setChecked] = React.useState(true);

  const handleChange = e => {
    e.persist();
    console.log(e.target.checked);
    setChecked({ checked: !e.target.checked });
  };

  return (
    <div className="App">
      <div className="container">
        <div className="list">
          <div className="search">Search</div>
          <div className="list">
            <ul>
              <input
                type="checkbox"
                checked={checked}
                onChange={handleChange}
                onClick={handleChange}
              />
            </ul>
            {JSON.stringify(checked)}
          </div>
        </div>
      </div>
    </div>
  );
}

Edit priceless-herschel-wqxzk

4 Answers

another thing you could do is add the following to the handle check

if(checked === true) {
  setChecked(false)
}else {
  setChecked(true)
}

Answered by kodamace on January 3, 2022

if your trying to just toggle checked or not checked, checkbox default is set you just have to return the checkbox as below, from what i can see your setting checked={checked}

     <div className="App">
          <div className="container">
            <div className="list">
              <div className="search">Search</div>
              <div className="list">
                <ul>
                  <input
                    type="checkbox"
                  />
                </ul>
                {JSON.stringify(checked)}
              </div>
            </div>
          </div>
        </div>




or you could also do the following what i do sometimes, if im doing anything wrong i would love to be corrected.

 const handleChange = e => {
    setChecked(!checked);
  };

<input
                type="checkbox"
                onChange={handleChange}
              />

Answered by kodamace on January 3, 2022

The main problem is you are firing the handleChange function two times.

Using the previous state of your checked state as:

const handleChange = e => {
   e.persist();
   setChecked(prevState => !prevState);
};

And also removing onChange from your input element as:

<input type="checkbox" checked={checked} onClick={handleChange} />

Just tested this solution and seemed to be working fine.

Answered by norbitrial on January 3, 2022

  const handleChange = e => {
    e.persist();
    console.log(e.target.checked);
    setChecked({ checked: !e.target.checked });
  };

This is failing because you are setting checked to an Object but you initialise the state with a boolean

   const [checked, setChecked] = React.useState(true);

Changing it to this, should work

  const handleChange = e => {
    setChecked(prevValue => !prevValue);
  };

Answered by user2340824 on January 3, 2022

Add your own answers!

Related Questions

Use of & operator in C++ Range Based Loop ..Confusing

2  Asked on December 22, 2021 by dmitriy-burtsev

   

‘for’ loop does not loop correctly

3  Asked on December 22, 2021

   

Traditional way of doing asnyc method in javascript

2  Asked on December 22, 2021 by faridavesko

     

How to compare using base class in derived class data

2  Asked on December 22, 2021 by sao-haruka

   

is it possible to use inline if with react components?

2  Asked on December 22, 2021 by handsome

 

Some questions about __init__.py

2  Asked on December 22, 2021 by theabc50111

   

Loop logic, stuck inside a infinite loop

2  Asked on December 22, 2021 by isythnic

     

WHY THE FUNCTION IS RETURNING NaN

3  Asked on December 22, 2021 by user13986133

   

How would one call getCurrentPosition() every second?

1  Asked on December 22, 2021 by user11965730

 

Submit button for multiple choice without using radio button

1  Asked on December 22, 2021 by rizki-prastyo

       

Can I get help formatting my future dates javascript?

2  Asked on December 22, 2021 by aiya-siddig

 

Python extract files from zip

1  Asked on December 22, 2021 by the-x-and-d

     

How can I make Electron channels more type safe?

1  Asked on December 22, 2021 by user1283776

   

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP