Why does using e.preventDefault() in this way in React not work?
I see in the docs that e.preventDefault() is supported, https://react.dev/learn/responding-to-events#preventing-default-behavior, however I am getting an error when I apply it in the following way.
In the returning JSX, I'm adding an onClick() event handler to one of the html elements, and passing into that handler as an argument an already-invoked deleteBtn() callback function (pic 1), the callback of which activates an alert box and console.logs something.
I have this deleteBtn() handler set to receive an e (event), and the first line of the function is e.preventDefault() so as to prevent the rest of the function from continuing to be executed. Or at least that what I assumed it would do. (pic 2)
When I set it up this way and load the page, the deleteBtn() is being invoked, and then it gets to my e.preventDefault() line and throws a "
Cannot read properties of undefined (reading 'preventDefault')
" error (pic 3)
Why is e.preventDefault() not being recognized here?Responding to Events – React
The library for web and native user interfaces
5 Replies
For the record I am aware I can also prevent it from auto-invoking with
onClick={()=>deleteBtn()}
, but I just wanted to understand why the `e.preventDefault()
approach doesn't workonClick={(e)=>deleteBtn(e)} ?
or just: onClick={deleteBtn}, because onClick expects a function definition and not a function execution/expression
so like this. This will immediately run deleteBtn() upon page load because it has the
()
. And I thought if I'd captured the implied event in my handler function, as 'e', I could just e.preventDefault(), like you would do in JavaScript?I think I'm confusing e.preventDefault() for being something that you just put on any function to stop it, when really it's only meant for certain events that automatically trigger something in the browser. ..?
Exactly. If you don't want a function to run, don't call it.
preventDefault() is to prevent a default action, normally after an event such as a button click.
For example on a form submit button when you press it it's default action is to submit a form. If you want to stop the form from being submitted, to do some validation for example , you use preventDefault().