Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use e.preventDefault() in a function with more parameters?

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    
   }); 
}
like image 521
Isabella Avatar asked Dec 17 '22 18:12

Isabella


2 Answers

Something like that?

<div onClick={(event)=> handleSubmit(event, param1, param2)}></div>
like image 73
AlexZvl Avatar answered Jan 25 '23 21:01

AlexZvl


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)} }/>
}
like image 43
wlh Avatar answered Jan 25 '23 22:01

wlh