React Js Build Multiple Checkbox With TypeScript Tutorial

A checkbox is a UI widget created with HTML that allows the user to make a binary selection. It is easy to make a binary selection.

In this React article, we will learn how to make a dynamic multi-checkbox in React TypeScript.

 

How To Create Multi-Checkboxes In React Functional Component

Step 1- Create Rect Environment

Primarily, we just have to use the create-react-app command in order to create a new React app. But before that, we have to make sure to have NPM and the Node on our development system:

npx create-react-app react-typescript-blog --template typescript

Further, we will enter into the project folder’s root:

cd react-typescript-blog

 

Step 2- Add Bootstrap In React

In React, we can write custom CSS to design the components. We can also use the frontend libraries to reduce the UI component designing time drastically.

Here, we will use the bootstrap library to design a dynamic checkbox component in React:

npm install bootstrap

Afterward, we have to register the bootstrap CSS path in the App.js file:

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

 

Step 3- Make Component File

To create the basic function component, we have to make the features directory and DynamicCheckbox.tsx file within the folder:

import React from 'react'
function DynamicCheckbox() {
  return (
    <div>DynamicCheckbox page</div>
  )
}
export default DynamicCheckbox

 

Step 4- Create Rect Dynamic Multiple Checkbox Component

Firstly, we need to create the variable that holds the REST_API. We are using a public API to create the dynamic checkbox list in React.

Then, we set the two-state using the useState hook for storing the checkbox values; one for the multicheck box and the other for the updated checkbox list.

The useEffect hook is used to perform side effects. We are using it to fetch the data from the server.

Now, we will use the custom function to delete the checkbox item from the checkbox list. On the other hand, to show the multi-checkbox, we have to use the map method.

Afterward, we will update the given code in the components/DynamicCheckbox.tsx file:

import React, { useState, useEffect } from "react";
const API = "https://reqres.in/api/users/";
interface DATA {
  id: any;
  first_name: string;
}
const DynamicCheckbox = () => {
  const [users, setUsers] = useState<Array<DATA>>([]);
  const [dataId, setDataId] = useState<Array<any>>([]);
  useEffect(() => {
    const fetchData = async (data: string) => {
      try {
        const response = await fetch(data);
        const users = await response.json();
        setUsers(users.data);
      } catch (e) {
        console.log(e);
      }
    };
    fetchData(API);
  }, []);
  const chooseCheckbox = (e: React.ChangeEvent<HTMLInputElement>) => {
    const id = parseInt(e.target.value);
    if (dataId.includes(id)) {
      const idCollection = dataId.filter((id) => id !== id);
      setDataId(idCollection);
    } else {
      const idCollection = [...dataId];
      idCollection.push(id);
      setDataId(idCollection);
    }
  };
  const remove = () => {
    const newList: DATA[] = users.filter(
      (item: any) => !dataId.includes(item.id)
    );
    setUsers(newList);
  };
  return (
    <div style={styles.container}>
      {users.length === 0 && <h4>Fetching Checkboxes ...</h4>}
      {users.length > 0 &&
        users.map((item: any) => (
          <div style={styles.checkbox} key={item.id}>
            <span style={styles.id}>{item.id}</span>
            <span style={styles.first_name}>{item.first_name}</span>
            <span>
              <input
                type="checkbox"
                value={item.id}
                onChange={chooseCheckbox}
                checked={dataId.includes(item.id) ? true : false}
              />
            </span>
          </div>
        ))}
      <button style={styles.button} onClick={remove}>
        Remove
      </button>
    </div>
  );
};
const styles: { [key: string]: React.CSSProperties } = {
  checkbox: {
    margin: "10px 0",
    padding: "14px 25px",
    backgroundColor: "rgb(238 237 247)",
    width: "100%",
    display: "flex",
    justifyContent: "space-between",
  },
  button: {
    marginTop: 15,
    color: "#ffffff",
    width: "100%",
    cursor: "pointer",
    padding: "15px 30px",
    border: "none",
    fontWeight: "bold",
    backgroundColor: "red",
  },
};
export default DynamicCheckbox;

 

Step 5- Register Multi Checkbox Component

Now, we must assign the component to the global component by importing the component into the App.js global component file:

import React from "react";
import "./App.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import DynamicCheckbox from "./features/DynamicCheckbox";
function App() {
  return (
    <div className="container mt-5">
      <h2 className="mb-4">React Multiple Dynamic Checkboxes Example</h2>
      <DynamicCheckbox />
    </div>
  );
}
export default App;

 

Step 6- Start React Server

Since we have reached the end of this React tutorial, we will execute the given command for starting the React server:

npm start

 

React JS Build Multiple Checkbox with TypeScript Tutorial

 

Conclusion

In this React tutorial, we have learned how to create multi-checkboxes in React TypeScript app.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *