how to add two onClick functions in React

20,913

Solution 1

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>;
  }
})

Solution 2

You can do this

class Mycomponent extends React.component {
 submit(e) {
  //handle event
 }
 render() {
  return <button className={s.button} onClick={this.submit.bind(this)} />
 }
}
Share:
20,913
bluegen1e
Author by

bluegen1e

Updated on September 15, 2020

Comments

  • bluegen1e
    bluegen1e over 3 years

    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)}}>
    
  • bluegen1e
    bluegen1e over 7 years
    hi thanks for responding. I tried your first method, but it doesn't submit the form. Instead it throws an error Uncaught TypeError: Cannot read property 'preventDefault' of undefined
  • bluegen1e
    bluegen1e over 7 years
    This is the submit function submit (e) { e.preventDefault(); if (this.refs.input.value.length === 5) { this.context.router.push('/where-to-buy/?zip=' + this.refs.input.value); } }
  • Buck Shlegeris
    Buck Shlegeris over 7 years
    I've changed my answer so it should work for that.