'onClick event firing off after render in React
I have a sidebar menu in react, when buttons are clicked in this sidebar I want to update state of a variable. However the event fires off on render instead of waiting for a click, help much appreciated!
Side Bar
return (
<>
<div id="container1">
<ProSidebar id='tester1'>
<SidebarHeader>
<h1>Header Title</h1>
</SidebarHeader>
<SidebarContent>
<Menu iconShape="square">
<MenuItem onClick={funx(1)} icon={<FiHome className='sideBarIcon'/>}></MenuItem>
<MenuItem icon={<FaList className='sideBarIcon'/>}></MenuItem>
<MenuItem icon={<FaRegHeart className='sideBarIcon'/>}></MenuItem>
<MenuItem icon={<RiPencilLine className='sideBarIcon'/>}></MenuItem>
<MenuItem icon={<BiCog className='sideBarIcon'/>}></MenuItem>
</Menu>
</SidebarContent>
<SidebarFooter>
<Menu iconShape="square">
<MenuItem icon={<FiLogOut />}>{x}</MenuItem>
</Menu>
</SidebarFooter>
</ProSidebar>
</div>
</>
);
And where the state gets set:
const [x, setX] = useState([]);
const funx = (e) => {
console.log(e);
setX(e);
}
I'd like to add if I remove the e parameter from funx, and only call funx in my menu, the onclick event seems to be working fine. However I want to pass 1/2/3/etc. depending on what's clicked
Solution 1:[1]
onClick={funx(1)} the code inside the brackets is evaluated at render, so you're actually calling the function. You want to pass a function reference. If you need to pass the 1 you could do:
<MenuItem onClick={() => funx(1)} ...>
Solution 2:[2]
Instead of setting the onClick event handler function like <MenuItem onClick={funx(1)} icon={<FiHome className='sideBarIcon'/>}></MenuItem>
You have to change the as like code given below:
<MenuItem onClick={() => funx(1)} icon={<FiHome className='sideBarIcon'/>}></MenuItem>
Or you can modify the event handler function as shown below:
const funx = (value) = (event) => {
console.log(value);
setX(value);
}
Now you can call the function as below:
<MenuItem onClick={funx(1)} icon={<FiHome className='sideBarIcon'/>}></MenuItem>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Madbreaks |
| Solution 2 | Jaied |
