Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda