Next.js Discord

Discord Forum

onClick event returning as undefined

Answered
Bendire's Thrasher posted this in #help-forum
Open in Discord
Avatar
Bendire's ThrasherOP
Within a component I am trying to add an onClick function to change state within my app. When the button is clicked the onClick function does get called but the event returns as undefined.

Here is the code for the onClick function:
function onClick (e) { e.preventDefault() }
If I console log it is undefined.

This is the section of my html where I added the function:

<a href='' > <button className="s10" id="reportOverview" onClick={onClick()}>Report Overview</button> </a>

Any help appreciated, thanks
Answered by Giant panda
Try this

onClick = {(e)=> onClick(e)}
View full answer

15 Replies

Avatar
Giant panda
Try this

onClick = {(e)=> onClick(e)}
Answer
Avatar
Bendire's ThrasherOP
Thanks for the reply.
I have made that change but I now can't see console logs anywhere
So it's quite hard to figure out what is going, the error has gone though
Avatar
Cape horse mackerel
are you logging at all?
I can see your function doesn't include console.log()
Avatar
Bendire's ThrasherOP
Yeah I am, just didn't include it in the code I sent over
The error has gone but the console logs aren't appearing in the browser or on my terminal.
When I add this to the function:
e.target.className="tocHighlightedText";
aha, it seems to be working now. Just that console logs aren't appearing for some reason
thanks
Avatar
Cape horse mackerel
ok then, just right click => apps => mark solution
Avatar
American black bear
You're doing
onClick = {onClick()}

But it should be
onClick = {onClick}


If you use onClick(), you're setting the onClick handler to the result of the onClick function
So you're initially running onClick() to get the result of onClick(), and since you're not passing any parameters e is undefined
Avatar
Giant panda
You r welcome, iam not sure because I always have done this way but I think is the way to pass events as parameters