3

I am a beginner with javscript So i will be thankful for explanation.

 {isolate_list.map((row) => {
                        return (
                          <FormControlLabel
                            control={
                              <Checkbox
                                color="primary"
                                checked={!!checked}
                                onChange={toggleCheckbox}
                                name="checkedA"
                              >
                                {" "}
                              </Checkbox>
                            }
                            label={row.isolatename}
                          >
                            {""}
                          </FormControlLabel>
                        );
                      })}

and i have this button

                    <Button
                      onClick={selectall}
                      style={{ margin: 50 }}
                      variant="outlined"
                      label="SELECT ALL ISOLATES"
                    >
                      SELECT ALL ISOLATES
                    </Button>

Can anyone help how can i use the button to select all checkboxes and in the same time i can select every checkbox alone by clicking on it? I beginn with this part but i am not sure

 const [checked, setChecked] = React.useState(true);
  const toggleCheckbox = (event) => {
    setChecked(event.target.checked);
  };

2
  • document.querySelectorAll("INPUT[type="checkbox"]"); Commented Dec 30, 2020 at 1:34
  • He means checking the selectbox, not selecting the dom node with query. Commented Dec 30, 2020 at 1:40

3 Answers 3

1

You should hold checkbox value's in the and give the state value as a property to each. For example

<Checkbox 
  color="primary" 
  onChange={toggleCheckbox}
  name="checkedA"
  value={checked}
>

And then in the onClick function

setChecked();
Sign up to request clarification or add additional context in comments.

4 Comments

When you give value prop to the checkbox, the checkbox will always have the value of the checked variable which you keep in state. You can think of it like two way binding. If you dont give checked variable as value prop, when you select the checkbox the onChange will be triggered and the checked variable will toggle . However, it wont be checked(visually on the browser and the dom) if the value of the state is changed. Only if you set the value as checked, it will always look for the checked value.
``` const [checked, setChecked] = React.useState(true); const toggleCheckbox = (event) => { setChecked(event.target.value); }; ``` Do you think this part is ok? i didn't understand how can i use setChecked to select all checkboxes?
You can use different state values for each checkboxes and set them all to true in the selectAll function. Or you can use a single object for all the checkboxes like const [checkedBoxes, setCheckedBoxes] = useState({first:false,second:false}) Then give value to the checkboxes and change values accordingly. value={checkedBoxes.first} In the
Is it possible to give two values to each checkboxe because we already have value={checked} so we can trigger every one on its own
1

The simplest implementations(without any form manager):

  1. Declare state to store our checked ids array.

const [checkedIds, setCheckedIds] = useState([]);

  1. implement handler.
const handleCheck = useCallback((id) => {
  return () => {
    setCheckedIds(prevIds => prevIds.includes(id) ? prevIds.filter(item => item !== id) : [...prevIds, id]);
  };
}, []);

  1. render our checkboxes and apply handler.
list.map(({ id, isolatename }) => (
  <FormControlLabel
    key={id}
    control={
      <Checkbox
        color="primary"
        checked={checkedIds.includes(id)}
        onChange={handleCheck(id)}
        name={`checkbox_${id}`}
      />
    }
    label={isolatename}
  />)
))

ps. in case if <Checkbox/> props 'onChange' returns callback like this (isChecked: boolean) => {} we can simplify (2) step.

const handleCheck = useCallback(id => {
  return isChecked => {
    setCheckedIds(prevIds => isChecked ? prevIds.filter(item => item == id) : [...prevIds, id]);
  };
}, []);

Comments

0

You may remember that it is React JS and not only JS that we are talking about.

In React you want to control data in the way of a state. There are a lot of ways to do so with check boxes, I'm contributing with one that you can see in the code snippet below:

import React, {useState} from "react";

export default function CheckBoxesControllers() {
  const [checkboxes, setCheckboxes] = useState(() => [
    { id: "0", checked: false },
    { id: "1", checked: false },
    { id: "2", checked: false },
  ]);

  const handleUpdate = (event) => {
    const { target: {id, checked} } = event;
    setCheckboxes(currentState => {
      const notToBeUpdated = currentState.filter(input => input.id !== id);
      return [
          ...notToBeUpdated,
        { id, checked }
      ]
    });
  }

  function toggleSelectAll() {
    setCheckboxes(currentState => currentState.map(checkbox => ({...checkbox, checked: !checkbox.checked})));
  }

  return (
      <>
          {checkboxes?.length ? (
              checkboxes.map((checkbox, index) => {
                return (
                    <input
                      checked={checkbox.checked}
                      id={checkbox.id}
                      key={index}
                      type="checkbox"
                      onChange={event => handleUpdate(event)}
                    />
                );
              })
          ) : <></>}
          <button onClick={toggleSelectAll}>Toggle Select All</button>
      </>
  )
}

This code is meant to serve you as an example of how to work properly with react state in the hook way, but there are other way, as you can see in the Documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.