I'm working on a form in React and I need to use event.preventDefault. At the same time I also need to pass other parameters to the parent function. I tried adding them normally using the code below, but it doesn't seem to work; how can I do that? I already looked at other questions but had no luck finding a solution.
handleSubmit = (event, param1, param2) => {
event.preventDefault();
this.setState(prevState => {
// piece of code where i need to use the other parameters
});
}
Something like that?
<div onClick={(event)=> handleSubmit(event, param1, param2)}></div>
Read this article here on Synthetic Events and Event Pooling to understand why this doesn't work the way you expect: https://reactjs.org/docs/events.html
But, you can pass parameters to a function called by your event handler. For example:
handleClick(param1, param2){
// no need to preventDefault here, you can't anyway, since you called it in onClick
this.setState(prevState=> {
// do something with param1 and param2
})
render() {
const param1 = "someVal";
const param2 = 0;
return <div onClick={e=> { e.preventDefault(); this.handleClick(param1,param2)} }/>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With