Reputation: 1067
I got these array in React which I want to use for writing and iterating through a bunch of menuitems. Im setting the state in my hook to false as default and are using the functions toggleMyIdOne and toggleMyIdTwo to update the state.
const [myIdOneToggler, setMyIdOne] = useState(false);
const [myIdOneToggler, setMyIdTwo] = useState(false);
const toggleMyIdOne= () => {
setMyIdOne(!myIdOneToggler);
}
const toggleMyIdTwo= () => {
setMyIdTwo(!myIdTwoToggler);
}
function Menu() {
const menuItems = [
{
id: "myIdOne",
state: "myIdOneToggler",
name: "toggleMyIdOne",
setState: "setMyIdOne",
label: "MyIdOne"
},
{
id: "myIdTwo",
state: "myIdTwoToggler",
name: "toggleMyIdTwo",
setState: "setMyIdTwo",
label: "MyIdTwo"
},
Further down Im returning this for updating the state of the checkbox once it is clicked.
{menuItems.map(item => (
<div className="grid-item">
<input onClick={item.name} type="checkbox" id={item.id} checked={item.state}/>
<label htmlFor={item.id}>{item.label}</label>
</div>
This is supposed to call the toggleMyIdOne and toggleMyIdTwo function. It works fine and as expected when it is not in a map function but in the mapfunction it seems to be something wrong with the way I am declaring the function name.
Im getting this errormessage:
Uncaught Invariant Violation: Expected
onClick
listener to be a function, instead got a value ofstring
type.
It is obvious that react wont recognize the string from my declared array with menuitems as a function but I cannot figure out how I shall declare this to get it to work. Or is it not possible to do like this to make the code more compact.
Upvotes: 0
Views: 36
Reputation: 3507
here you are passing a String to click props wich it should accept only functions! to solve this u can do:
{menuItems.map(item => (
<div className="grid-item">
<input onClick={()=>checkfunction(name)} type="checkbox" id={item.id} checked={item.state}/>
<label htmlFor={item.id}>{item.label}</label>
</div>
and if u want to fire each hook
const checkfunction=name={
if(name==="toggleMyIdOne")
setMyIdOne(!myIdOneToggler);
else
setMyIdTwo(!myIdTwoToggler);
}
Upvotes: 1