Way to determine checkbox checked in react (useState)
Asked Answered
M

4

12

This is my first time to develop a react application. I tried to implement checkboxes in each row of a table and check which of the rows are selected.

I used useState hook to make checked and onChange events, but seems the values are not refreshing when I check then uncheck the checkbox.

I would like to ask how to add a logic to remove the unticked values on the hooks.

T1 Checkbox A- Checked Checkbox B- Checked CheckedMap- A,B

T2 Checkbox B- Unchecked CheckedMap- A,B // Unticked Checkbox B is also stored in CheckedMap

Thank you for your help.

export default function({ infinite }) {
  const [checkedMap, setCheckedMap] = useState(new Map());
}

const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    modifiedMap.set(transaction_seq, !checkedMap.get(transaction_seq));
    setCheckedMap(modifiedMap);
  };

const columns = [
    {
      Header: "Transaction(s)",
      className: "left",
      columns: [
        {
          id: "checkbox",
          accessor: "checkbox",
          Cell: ({ row }) => {
            return (
              <input
                type="checkbox"
                className="checkbox"
                checked={checkedMap.get(row.original.transaction_seq)}
                onChange={() =>
                  handleCheckedChange(row.original.transaction_seq)
                }
Margaretmargareta answered 29/5, 2019 at 9:6 Comment(2)
Is this really your code? It does not look like a valid decleration of a react function component.Cerebrovascular
In pre-react times this had been done with one line of the code...Coalfield
C
22

This is the way how to use controlled checkbox with react useState hook.

const { useState } = React; // --> for inline use
// import React, { useState } from 'react';  // --> for real project


const App = () => {
  const [checked, setChecked] = useState(false)
  const handleClick = () => setChecked(!checked)
  
  return <input onClick={handleClick} checked={checked} type="checkbox" />
};


ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Cunningham answered 12/9, 2019 at 14:37 Comment(3)
what if i have 30 checkboxes? Or the data is coming from an external API?Hackery
Please, have a look on this answer for dynamic checkbox data: #63021045Cunningham
it is better to use onChange because you may see this error You provided a checked prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultChecked. Otherwise, set either onChange or readOnlyFujio
E
2

You may get an error using onClick for the function. Instead using onChange:

    import { useState} from "react";

    export default function App() {
      const [checked, setChecked] = useState<boolean>(true);
      
      return (
        <input name="checked" type="checkbox" checked={checked} 
          onChange={e => setChecked(!checked)} />
      )
    }
Enrique answered 30/11, 2021 at 3:8 Comment(1)
Really simple and clean!Phosgene
S
1

You got an event object when you use onChange. Use that event to check if the checkbox is checked or not

//here, you got access to event object
onChange={(e) =>
  handleCheckedChange(e, row.original.transaction_seq)
}

Then, in your function just use that event to check the status

const handleCheckedChange = (e, transaction_seq) => {
  if(e.target.checked == true){
    //do something
  }
  if(e.target.checked != true){
    //do something else
  }
};
Skullcap answered 27/2, 2023 at 6:32 Comment(0)
H
0

You can check the check status in map and then decide whether to set the value or delete it

const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    if(checkedMap.get(transaction_seq)) {
        modifiedMap.delete(transaction_seq)
    } else {
        modifiedMap.set(transaction_seq, true);
    }
    setCheckedMap(modifiedMap);
  };
Hatband answered 29/5, 2019 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.