Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda