Reputation: 83
Here is my state,
const [partners, setPartners] = useState([
{
accessKeyId: "abc123",
partnerName: "karta",
status: "active"
},
{
accessKeyId: "qwe112",
partnerName: "karta",
status: "inactive"
},
{
accessKeyId: "zxc358",
partnerName: "special",
status: "inactive"
},
])
const [isActive, setActive] = useState({
active: true,
inactive: false
});
How to make the switch button is true when status is active and button is false when the status is inactive? and how to make it toggle the status when I click the switch button.
{partners.map((partner, index) => (
<TableRow key={partner.accessKeyId}>
<TableCell align="left">{partner.accessKeyId} </TableCell>
<TableCell align="left">********* </TableCell>
<TableCell align="left">{partner.partnerName} </TableCell>
<TableCell align="left">
<FormGroup>
<FormControlLabel
value={index}
onChange={() => handleChange(index)}
control={<Switch
value={isActive}
checked={`isActive.${partner.status}`}
/>}
/>
</FormGroup>
Upvotes: 0
Views: 2107
Reputation: 221
Why do you use isActive
variable? If I understand the question correctly, You can use partners
status instead, changing it to isActive
boolean property.
<FormGroup>
<FormControlLabel
value={index}
id={partner.accessKeyId}
onChange={() => handleChange(id)}
control={<Switch
value={partner.isActive}
checked={partner.isActive}
/>}
/>
</FormGroup>
to toggle status in handleChange
function you may copy Partners
array and change isActive
property based on accessKeyId
const clonedPartners = partners.map(el => {...el});
const updatedPartners = clonedPartners(el => {
if (el.accessKeyId === id){
el.isActive = !el.isActive;
}
}
and to update Partners
use setPartners(updatedPartners)
Upvotes: 0
Reputation: 889
Please find the updated code below:
#Handle Change Function
const handleChange = (keyId) => {
const newData = partners.map(item => {
if(item.accessKeyId === keyId) {
item.status = item.status === 'active' ? 'inactive' : 'active';
}
return item;
})
setPartners(newData);
}
Now the JSX part in which how you will embed onChange function
{partners.map((partner, index) => (
<TableRow key={partner.accessKeyId}>
<TableCell align="left">{partner.accessKeyId} </TableCell>
<TableCell align="left">********* </TableCell>
<TableCell align="left">{partner.partnerName} </TableCell>
<TableCell align="left">
<FormGroup>
<FormControlLabel
value={index}
control={<Switch
checked={partner.status === 'active'}
onChange={() => handleChange(partner.accessKeyId)}
/>}
label={partner.status}
/>
</FormGroup>
I hope this may be helpful to you.
Kindly, let me know in case of any concerns.
Upvotes: 2