Reputation: 21
I am trying to create a sidebar that has a dynamic amount of toggle buttons created from an object(keys,values). I can't seem to get the "key" value to change the corresponding "value" in my state. I am using @material-ui/lab/ToggleButton as my button components and I can retrieve the value selected but I can't find the index or value that's being changed. I created a sandbox for people to see the exact issue I am working with. I've tried looking in the html attributes(and creating my own), but I still am not able to get it. Even a suggestion to try some other way would be appreciated, though I'd like to see I am able to get it done with what I have already. Thank you.
Upvotes: 0
Views: 487
Reputation: 4706
You can use inline function with a key param in the onClick handler:
import React, { useState } from "react";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";
export default function MultipleToggleSelection() {
const mylist = {
a: "1",
b: "1",
c: "1",
d: "1"
};
const [oneTwoThree, setOneTwoThree] = useState(mylist);
const handleToggle = (key, value) => {
oneTwoThree[key] = value;
setOneTwoThree({...oneTwoThree});
};
return (
<div>
<div>{JSON.stringify(oneTwoThree, null, ' ')}</div>
<List>
{Object.keys(oneTwoThree).map((key, index) => (
<ListItem key={key}>
<ToggleButtonGroup
value={oneTwoThree[index]}
exclusive
onChange={(event, value) => handleToggle(key, value)}
>
<ToggleButton value="1">1</ToggleButton>
<ToggleButton value="2">2</ToggleButton>
<ToggleButton value="3">3</ToggleButton>
</ToggleButtonGroup>
{key}
</ListItem>
))}
</List>
</div>
);
}
Upvotes: 1