hey ~ I'm trying to fire a submit function and a google click event on the same onClick in React. How do I do this in React?
This is the code:
<button className={s.button} onClick={this.submit} onClick={ () => {gaClickEvent('where-to-buy', 'submit' , undefined)}}>
The first way to perform multiple onClick events in React is to write your logic in a single function, and then call that function inside of the onClick event handler. To learn more about the onClick event handler in React, check out my tutorial on React onClick Event Handling with Examples.
Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.
You could either do onClick={() => props. headlinesClicked(); props. getData()} , or extract it to a new function/method that does both calls, then invoke it with onClick={myNewMethod} or onClick={() => myNewMethod()} . Save this answer.
Rather than creating a new component instance (if we already have one), sometimes we'll want to copy it or add custom props/children to the component so we can retain the same props it was created with. We can use React. cloneElement() to handle this for us.
You can do this
class Mycomponent extends React.component {
submit(e) {
//handle event
}
render() {
return <button className={s.button} onClick={this.submit.bind(this)} />
}
}
There are two ways of doing this.
To start with, you can put two statements in the click handler that you're defining inline with the ES6 function literal syntax.
<button
className={s.button}
onClick={ (e) => {
gaClickEvent('home-where-to-buy', 'submit' , undefined);
this.submit(e);
}} >
But this is slightly more code that I'd be comfortable putting in an onClick handler. If I were you, I'd separate this logic out into a handler method on the component. Eg:
var MyComponent = React.createClass({
handleClick () {
gaClickEvent('home-where-to-buy', 'submit' , undefined);
this.submit();
},
render () {
return <button
className={s.button}
onClick={(e) => this.handleClick(e)} >
I am a button!
</button>;
}
})
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