onClick event returning as undefined
Answered
Bendire's Thrasher posted this in #help-forum
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:
If I console log it is undefined.
This is the section of my html where I added the function:
Any help appreciated, thanks
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
15 Replies
Giant panda
Try this
onClick = {(e)=> onClick(e)}
Answer
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
Cape horse mackerel
are you logging at all?
I can see your function doesn't include
I can see your function doesn't include
console.log()
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
Cape horse mackerel
ok then, just right click => apps => mark solution
American black bear
You're doing
But it should be
If you use onClick(), you're setting the onClick handler to the result of the onClick function
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
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