React JS Count number of checkboxes are checked

To count the number of checkboxes that are checked in a React JS application, you can maintain a state that keeps track of the checked checkboxes. Here's a simple example to demonstrate this:

1. First, create a new React component that renders multiple checkboxes and maintains their checked state:

import React, { useState } from 'react';

const CheckBoxList = ({ checkboxes }) => {
  const [checkedState, setCheckedState] = useState(
    new Array(checkboxes.length).fill(false)
  );

  const handleOnChange = (position) => {
    const updatedCheckedState = checkedState.map((item, index) =>
      index === position ? !item : item
    );

    setCheckedState(updatedCheckedState);
  };

  return (
    <div>
      {checkboxes.map((item, index) => (
        <div key={index}>
          <label>
            <input
              type="checkbox"
              checked={checkedState[index]}
              onChange={() => handleOnChange(index)}
            />
            {item}
          </label>
        </div>
      ))}
    </div>
  );
};

export default CheckBoxList;

2. Next, create a parent component that uses the CheckBoxList component and counts the checked checkboxes:

import React from 'react';
import CheckBoxList from './CheckBoxList';

const App = () => {
  const checkboxes = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];

  return (
    <div>
      <h1>Checkboxes Example</h1>
      <CheckBoxList checkboxes={checkboxes} />
    </div>
  );
};

export default App;

3. Modify the App component to count the checked checkboxes by lifting the state up from the CheckBoxList component:

import React, { useState } from 'react';
import CheckBoxList from './CheckBoxList';

const App = () => {
  const checkboxes = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
  const [checkedState, setCheckedState] = useState(
    new Array(checkboxes.length).fill(false)
  );

  const handleCheckboxChange = (index) => {
    const updatedCheckedState = checkedState.map((item, idx) =>
      idx === index ? !item : item
    );
    setCheckedState(updatedCheckedState);
  };

  const countCheckedCheckboxes = () => {
    return checkedState.filter(Boolean).length;
  };

  return (
    <div>
      <h1>Checkboxes Example</h1>
      <CheckBoxList
        checkboxes={checkboxes}
        checkedState={checkedState}
        handleCheckboxChange={handleCheckboxChange}
      />
      <p>
        Number of checked checkboxes: <strong>{countCheckedCheckboxes()}</strong>
      </p>
    </div>
  );
};

export default App;

4. Finally, update the CheckBoxList component to accept the new props:
import React from 'react';

const CheckBoxList = ({ checkboxes, checkedState, handleCheckboxChange }) => {
  return (
    <div>
      {checkboxes.map((item, index) => (
        <div key={index}>
          <label>
            <input
              type="checkbox"
              checked={checkedState[index]}
              onChange={() => handleCheckboxChange(index)}
            />
            {item}
          </label>
        </div>
      ))}
    </div>
  );
};

export default CheckBoxList;
Now, when you check or uncheck any of the checkboxes, the count of checked checkboxes will be displayed and updated accordingly.

Most Helpful This Week
Calculator How to create Functional Component? Example of React JS with Material UI components React JS onClick event handler React Props Loop inside React JSX Integrate Bootstrap with ReactJS Application React Components Form Validation React JS Blog CRUD operation How to pass properties from parent component to child component in React JS? Carousel Weather Finder Getting Started with React and Hello World Example How to set property values using expression? Working with Forms, Inputs and onChange Events in ReactJs Dice Game React Static Website with Material UI theme How to get a clicked HTML element in React? Display JSON Data in React JS Memory Game Cannot call non-function <variable> error in Golang Using this keyword access component properties and methods onMouseDown and onMouseUp Event handling in ReactJs Random Quote Generator How to use React-Bootstrap component? How to use arrow function in React stateless components? Embed JavaScript Expressions in JSX Search Autocomplete Create Functional Component using ES6 Arrow Syntax How to perform computation inside expression using ternary operator? React JS update Div content on click Search and Filter List Records Component displays Height and Width on window resize How to render raw HTML content in React JS? React JSX Data Table How to create simple React Router to navigate multiple pages? How to pass data from child component to its parent in ReactJS? Voting System Google Map Check checkbox is Checked or Unchecked How to handle events using expressions inside JSX? React Elements Bill and Discount Calculator How to build and use a custom react component from scratch? How to render one component in another component in React JS? Compass Clock Arrange Game How to pass an Argument to a Method used inside JSX expression? React JS get Tag Name and Inner Text on Click Random Meme Generator Glyphicon Rating Star component How to use onChange and onClick event in React JS? How to show hide component on Click in React JS? Tic Tac Toe Example of React Bootstrap Datatable How to use function inside JSX expression? onClick Event binding and get event name in ReactJs Form Container Check which Radio button is Selected or Clicked How to use createElement in React JS? Create React App