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

Pygame doesn’t play mp3 files tagged with mutagen

1  Asked on January 14, 2021 by droptop

       

Average by group for ‘n’ number of rows per group – R

2  Asked on January 14, 2021 by codemaster

       

Non consecutive combinations of array elements in R

4  Asked on January 13, 2021 by guest2341

 

How to mutate complex object with nested array with SWR?

1  Asked on January 13, 2021 by geraltdiesocke

   

Why do I not see a text box to add a menu item to a menustrip

1  Asked on January 13, 2021 by justsomeguytn

   

Alembic. ModuleNotFoundError in env.py

2  Asked on January 13, 2021 by mroldsir

     

What type in c# is most like an expression in R and why?

1  Asked on January 12, 2021 by kirsten-greed

     

Difference between two loops

4  Asked on January 12, 2021 by mszros-zoltn

     

How can i do a request an external url?

0  Asked on January 12, 2021 by mikkylekyle

   

Ask a Question

Get help from others!

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