here i tried many ways to get the values from the dynamic generated chekcboxes in react js but i failed, help me to solve this issues.. am getting the problems like
"Uncaught TypeError: Cannot set properties of undefined"
or anyone of the states like "{Name: "Module2",View:false,Create:false,Edit:false,Delete:false}",
the values should be update in the handlechange itself.
const DynamicCB = ()=>{
const modules = ["Module1", "Module2","Module3"]
const [state,setState] = useState([{
Name:'',
View:false,
Create:false,
Edit:false,
Delete:false
}])
const handlechange = (name ,i) =>event=>{
console.log(name)
const Data=[...state]
if(Data.includes(event.target.name)){
Data[i][name] = event.target.checked
setState(state,Data)
}else{
Data[i].Name = event.target.name
Data[i][name] = event.target.checked
setState(state,Data);
}
return(<>
<div className="container">
<div className="row">
<h2>Modules</h2>
</div>
{
modules.map((item,i)=>(
<div className="row" key={i}>
<div className="col-sm">
<h4>{item}</h4>
</div>
<div className="col">
<input type="checkbox" name={item} className="m-2"
onChange={handlechange('View',i)}/>View
<input type="checkbox" name={item} className="m-2"
onChange={handlechange('Create',i)}/>Create
<input type="checkbox" name={item} className="m-2"
onChange={handlechange('Edit',i)}/>Edit
<input type="checkbox" name={item} className="m-2"
onChange={handlechange('Delete',i)}/>Delete
</div>
</div>
))
}
</div>
</>)
}
in my try it shows any one of the below array of object or, it shows an error like "Cannot set properties of undefined (setting 'Name')". i need the state values like as below
[
{ Name: "Module1",View:true,Create:false,Edit:false,Delete:false},
{ Name: "Module2",View:false,Create:false,Edit:false,Delete:false},
{ Name: "Module3",View:false,Create:true,Edit:true,Delete:false}
]
You can initialize the state (using the useState callback) and update each module state using moduleName and the operation name ("View", "Edit", "Create", "Delete")like below.
const modules = ["Module1", "Module2", "Module3"];
const [state, setState] = useState(() =>
modules.map((module) => {
return {
Name: module,
View: false,
Create: false,
Edit: false,
Delete: false
};
})
);
const handlechange = (name, i) => (event) => {
const moduleName = event.target.name;
const actionName = name;
setState((prev) => {
return prev.map((module) => {
if (module.Name === moduleName) {
return { ...module, [actionName]: event.target.checked };
}
return module;
});
});
};