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
Aucun commentaire:
Enregistrer un commentaire