Stateful Checkbox with Multiple Selection

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to create a stateful checkbox with multiple selection using React. This lab will guide you through the process of rendering a checkbox list, updating its state, and passing the selected value/values to the parent component using a callback function. By the end of this lab, you will be able to create a reusable checkbox component that can be used in any React project.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/list_keys("`Lists and Keys`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38357{{"`Stateful Checkbox with Multiple Selection`"}} react/event_handling -.-> lab-38357{{"`Stateful Checkbox with Multiple Selection`"}} react/list_keys -.-> lab-38357{{"`Stateful Checkbox with Multiple Selection`"}} react/hooks -.-> lab-38357{{"`Stateful Checkbox with Multiple Selection`"}} react/use_state_reducer -.-> lab-38357{{"`Stateful Checkbox with Multiple Selection`"}} end

Stateful Checkbox With Multiple Selection

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This code renders a list of checkboxes and sends the selected value(s) to the parent component using a callback function. Here are the steps to create it:

  1. Use the useState() hook to initialize the data state variable with the options prop.
  2. Create a toggle function that updates the data state variable with the selected option(s) and calls the onChange callback function with them.
  3. Map the data state variable to generate individual checkboxes and their labels. Bind the toggle function to the onClick handler of each checkbox.
const MultiselectCheckbox = ({ options, onChange }) => {
  const [data, setData] = React.useState(options);

  const toggle = (index) => {
    const newData = [...data];
    newData[index] = {
      ...newData[index],
      checked: !newData[index].checked
    };
    setData(newData);
    onChange(newData.filter((item) => item.checked));
  };

  return (
    <>
      {data.map((item, index) => (
        <label key={item.label}>
          <input
            type="checkbox"
            checked={item.checked || false}
            onChange={() => toggle(index)}
          />
          {item.label}
        </label>
      ))}
    </>
  );
};

Here is an example of how to use it:

const options = [{ label: "Item One" }, { label: "Item Two" }];

ReactDOM.createRoot(document.getElementById("root")).render(
  <MultiselectCheckbox
    options={options}
    onChange={(selected) => {
      console.log(selected);
    }}
  />
);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Stateful Checkbox With Multiple Selection lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like