I want to change value of index 0 object 'sm:true' and on second check create a new object and change value of 'xl:true' of index 1
const [size, setSizes] = useState([{sm:false, md:false, lg:false, xl:false,}])
const sizeHandler=(index, value)=>
{
on first check index is 0 & value = sm:true
on secondcheck index is 1 & value = xl:true
if(index===0
size.map(()=>{
setSize()
})
}
<FormGroup>
<FormControlLabel control={<Checkbox />} label="SM" onChange={()=>sizeHandler(0,{sm:true})} />
</FormGroup>
<FormGroup>
<FormControlLabel control={<Checkbox />} label="XL" onChange={()=>sizeHandler(1,{xl:true})} />
</FormGroup>
result should be like this: [{sm:true, md:false, lg:false, xl:false}, {sm:false, md:false, lg:false, xl:true}]
I'm relatively new to js - so hopefully, someone wiser will update/correct this attempted-answer below.
Without going into the UI (FormGroup, FormControlLabel), will try to focus on the actual task/requirement at hand.
Given:
Requirement: Based on the 'index', create additional array-element/s and update the corresponding element (for example if 'index' is 1, then update the 2nd element) with the value being sent used to replace only a part of the object identified at 'index' position.
Snippet for quick-checking:
const fixedObj = {
sm: false,
md: false,
lg: false,
xl: false
};
const dynamicArray = [fixedObj];
/* const [size, setSizes] = useState([{sm:false, md:false, lg:false, xl:false,}]) */
const sizeHandler = (index, value) => {
// First capture the current array-length
const currArrLen = dynamicArray.length;
if (!(index < currArrLen)) { // if 'index' is NOT within the array-length
for (let i = currArrLen; i < index; i++) { // increase the array-size to match index
dynamicArray.push(fixedObj); // initialize each new array-element using the fixedObj tempate
};
};
// Now, target the specific array-element, use spread operator to use template, followed by 'value'
// and update the specific array-element.
dynamicArray[index] = {
...fixedObj,
...value
};
};
sizeHandler(0, {
sm: true
});
console.log('on first check, update sm to true at index 0, array: ', dynamicArray, '\n\n\n');
sizeHandler(1, {
xl: true
});
console.log('on second check update xl to true at index 1, array: ', dynamicArray, '\n\n\n');