I am trying to make a switch in react which renders a particular icon if a state is false and another one if the state is true...I am trying to change the state if a button is clicked..But I am getting this error:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
this is the javascript of the error giving component:
const [wantsPassword, setWantsPassword] = useState(false)
and this is the JSX:
<IconButton onClick={setWantsPassword(!wantsPassword)} >
{wantsPassword?<VisibilityOffIcon/>:<VisibilityIcon />}
</IconButton>
Where am i going wrong?
The issue is that you call the set function on render , rather than on click. You need to make onClick
a function, not a function invocation:
<IconButton onClick={() => setWantsPassword(!wantsPassword)} >
You're calling the function in onClick
on every render <IconButton onClick={setWantsPassword(!wantsPassword)} >
Change it to:
<IconButton onClick={() => setWantsPassword(!wantsPassword)}>
You shouldn't execute the function inside the onClick. Instead do like below:-
<IconButton onClick={() => setWantsPassword(!wantsPassword)} >
你应该像这样使用箭头函数:
<IconButton onClick={() => setWantsPassword(!wantsPassword)} >
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.