DEV Community

Mayank Kashyap
Mayank Kashyap

Posted on

Multiple Checkbox Form in React Js

Multiple Checkbox list is very often seen on the websites like Amazon, Flipkart etc.

Image description

So today we are going to build multiple checkbox list from scratch using React.
So, our final result will look like the gif below
Image description

This is App.js, make a React project and you will find it over there.
You can create a separate file for the Checkbox list or simple write your code in the App.js but I prefer to create a new file for Checkbox list. Import the Checkbox from the File Checkbox.js and make it a component. Styling is up to you. You can style it anyway you want.

import "./styles.css";
import Checkbox from "./Checkbox";

export default function App() {
  return (
    <div className="App">
      <Checkbox />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is our Checkbox.js

import React from "react";

const Checkbox = () => {

  const list = [
    "checkbox1",
    "checkbox2",
    "checkbox3",
    "checkbox4",
    "checkbox5"
  ];

  return (
    <div
      className="selector-bg"
      style={{ background: "aliceblue", height: "100vh", margin: "20px" }}
    >
      <div>
        <h1
          style={{
            textAlign: "center",
            fontWeight: "bold",
            textTransform: "uppercase",
            fontSize: "20px"
          }}
        >
          Select List
        </h1>
        <form>
          <div style={{ padding: "20px" }}>
            {list.map((val) => (
              <div
                style={{
                  display: "flex",
                  backgroundColor: "yellowgreen",
                  padding: "10px",
                  margin: "12px"
                }}
                key={val}
              >
                <input
                  type="checkbox"
                  id={val}
                  value={val}
                  name={val}
                  style={{ marginRight: "10px" }}
                />
                <label for={val}>{val}</label>
              </div>
            ))}
          </div>
        </form>
      </div>
    </div>
  );
};

export default Checkbox;

Enter fullscreen mode Exit fullscreen mode

So in the Checkbox.js we have firstly made the list of all the tags which we want to display and to keep everything simple I have named them checkbox1, checkbox2, checkbox3 and so on you can also replace them with some real tags like brand names, color names or whatever you like.

const list = [ "checkbox1", "checkbox2", "checkbox3", "checkbox4", "checkbox5"];

we are making this list so that we don't need to hardcode tags and write repetitive code, instead of that we can simply use map on the list of the tags and display them by writing code once.

<div
className="selector-bg"
style={{ background: "aliceblue", height: "100vh", margin: "20px" }}
>
<div>
<h1
style={{
textAlign: "center",
fontWeight: "bold",
textTransform: "uppercase",
fontSize: "20px"
}}
>
Select List
</h1>
<form>
<div style={{ padding: "20px" }}>
{list.map((val) => (
<div
style={{
display: "flex",
backgroundColor: "yellowgreen",
padding: "10px",
margin: "12px"
}}
key={val}
>
<input
type="checkbox"
id={val}
value={val}
name={val}
style={{ marginRight: "10px" }}
/>
<label for={val}>{val}</label>
</div>
))}
</div>
</form>
</div>

In the code written above we have only done some styling and created a form, iterated over the list of tags and displayed them. After all this we will get the output something like the image below.

Image description

Now, lets add state and add logic to make things work

Import useState() from React

import {useState} from 'react'

A). Add a state checked to keep track of all the tags which are checked.
const [checked, setChecked] = useState([]);

B). Add onChange Event handler on the input field
onChange={() => handleToggle(val)}

C). Write the logic for the handleToggle function, so that whenever a box is checked or unchecked the handleToggle function get triggered.

const handleToggle = (val) => {
    var currentIndex = checked.indexOf(val);
    var newArr = [...checked];

    if (currentIndex === -1) {
      newArr.push(val);
    } else {
      newArr.splice(currentIndex, 1);
    }

    setChecked(newArr);
  };
Enter fullscreen mode Exit fullscreen mode

Handle Toggle function doing following things
1). It is finding the index of the tag in the checked array,
if the tag is present then we will get the index, otherwise we will get -1
2). we are creating another array newArray and initializing it with all the tags which are currently in the checked array, in simple words we are making copy.
3). If the currentIndex is -1, it means the tag is not present in the array so we are pushing it in the newArr by using push() method.
4). If the currentIndex is not equal to -1 it means the tag is already checked thus present in the checked array, so we are removing it using splice() method.
5). At last we are setting the checked array using setChecked(newArr);

To display all the checked tags we are adding another div which get diplayed only when the size of checked array is greater than 0 means the checked array is having atleast one element

 <div style={{ display: "flex", backgroundColor: "gray" }}>
        {checked.map((item) => (
          <p
            key={item}
            style={{
              margin: "10px",
              color: "whitesmoke",
              border: "2px solid greenyellow",
              padding: "2px"
            }}
          >
            {item}
          </p>
        ))}
      </div>
Enter fullscreen mode Exit fullscreen mode

The link for the final code of Checkbox.js
https://github.com/MaYaNkKashyap681/React-Native-Features-Implementation/blob/main/Selection%20Checkbox%20in%20React.js

Top comments (0)