Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Getting multiple values for checkboxes with dynamic data react

Get All values of checkboxes from dynamic values

import * as React from "react";
import Checkbox from "@mui/material/Checkbox";
import FormControlLabel from "@mui/material/FormControlLabel";
import axios from "axios";

export default function Checkboxes() {
const [users, setUsers] = React.useState([]);

const [isChecked, setIsChecked] = React.useState(() =>
users.map((i) => false)
);

React.useEffect(() => {
getUsers();
}, []);
const getUsers = async () => {
 try {
  const response = await axios.get(
    "https://jsonplaceholder.typicode.com/users"
  );
  setUsers(response.data);
 } catch (error) {
  console.error(error);
 }
 };

  const isCheckboxChecked = (index, checked) => {
  setIsChecked((isChecked) => {
  return isChecked.map((c, i) => {
    if (i === index) return checked;
    return c;
  });
  });
  };
  console.log(isChecked);

 return (
 <div>
  {users.map((checkbox, index) => {
    return (
      <FormControlLabel
        key={index}
        control={
          <Checkbox
            checked={isChecked[index]}
            onChange={(e) => isCheckboxChecked(index, e.target.checked)}
          />
        }
        label={checkbox.name}
      />
    );
   })}
   <pre>{JSON.stringify(isChecked, null, 4)}</pre>
   </div>
   );
   }

i'm trying to do like this. https://codesandbox.io/s/69640376-material-ui-react-multiple-checkbox-using-tabs-8jogw?file=/demo.js but this has static data.

this is what i have done so far https://codesandbox.io/s/festive-euclid-w3dzpq?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you need the same functionality as the first sandbox, then you need to update somehow your "checked" array after you fetch the users.

Currently this array is not updated, so you never see true/false values

Try this

  const getUsers = async () => {
    try {
      const response = await axios.get(
        "https://jsonplaceholder.typicode.com/users"
      );
      await setUsers(response.data);
      setIsChecked(() => response.data.map((i) => false));
    } catch (error) {
      console.error(error);
    }
  };

sandbox

If you don't want to use a function, you can instead use an array

  const [isChecked, setIsChecked] = React.useState([]);

  React.useEffect(() => {
    getUsers();
  }, []);
  const getUsers = async () => {
    try {
      const response = await axios.get(
        "https://jsonplaceholder.typicode.com/users"
      );
      await setUsers(response.data);
      setIsChecked(Array.from({length: response.data.length}, i => i = false))
    } catch (error) {
      console.error(error);
    }
  };

In order to clear the "uncontrolled state" warnings/errors, change this line

          <Checkbox
            checked={isChecked[index] == null  ? false : isChecked[index]}
            onChange={(e) => isCheckboxChecked(index, e.target.checked)}
          />

Checkbox must have an initial controlled state of true or false and not null/undefined.

about 4 years ago · Juan Pablo Isaza Report

0

I've checked your code and found that you should issue in your "isCheckboxChecked" method.

const isCheckboxChecked = (index, checked) => {
    isChecked[index] = checked;
    setIsChecked([...isChecked]);
};

Another issue was you should wait till you get your response from API, so we are only setting checkboxes when we have users.

React.useEffect(() => {
    if (users.length) setIsChecked(users.map((i) => false));
}, [users]);

Hope this helps😁

I've already updated your sandbox. https://codesandbox.io/s/festive-euclid-w3dzpq?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!