React JS Build Multiple Checkbox with TypeScript Tutorial

Last updated on: by Digamber

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

But do you know how to create a checkbox component in Rect? Not only but also, how to make a dynamic multi-checkbox in React? If your answer is no. Then fret not!

In this article, you will learn how to build multi-checkboxes in React TypeScript.

You’ll go through a complete overview of how to create dynamic multi-checkboxes in React functional component. How to use React useState, useEffect hooks in a React TypeScript app. How to make GET request in React using Fetch and Public API. Last but not least. How to set up and use Bootstrap 5 in React JS app.

Create React Environment

When you first create the React app, you must have Node and NPM configured in your machine.

This is the simplest way to create a new project. On the terminal, you have to type the npx create-react-app followed by your project name.

Run the command by pressing enter.

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

Now, you will need to enter into the project folder’s root.

cd react-typescript-blog

Add Bootstrap in React

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

We will use the bootstrap library to design a dynamic checkbox component in React.

npm install bootstrap

Half work is done, now the imperative thing is to register the bootstrap CSS path in the App.js file.

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

Not just checkbox but with Bootstrap, you are now ready to create many other UI components in React.

Make Component File

A functional component is a pure JavaScript function that makes the component development extremely facile and flexible.

To create the basic function component, make the features directory and a DynamicCheckbox.tsx file within the folder.

This is how you define a basic function component in React TypeScript.

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

Create React Dynamic Multiple Checkbox Component

First, you create the variable that holds the REST_API; we are using a public API to create the dynamic checkbox list in React.

Set the two-state using the useState hook for storing the checkbox values; one for the multi-check box list and another 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.

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

Apart from bootstrap, we are using the styles object in React with React.CSSProperties.

Update code into 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;

Register Multi Checkbox Component

After creating the multi-checkbox component, 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;

Start React Server

Move on to the terminal, then execute the following command to start the React server.

npm start

You may use the following URL to view the app.

http://localhost:3000

React JS Build Multiple Checkbox with TypeScript Tutorial

Conclusion

In React, Hooks are used to managing the component’s stateful logic. It gives utter independence to a user from independent testing and code reusability viewpoint.

To set the dynamic checkbox values, we used useState and useEffect to fetch the data from the API. Apart from that, to delete the multi-checkboxs’ value, we set the onChange event handler on the checkbox property.

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

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.