10

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)}}>
1
  • why not call the second onClick on the first one? Commented Sep 14, 2016 at 20:05

2 Answers 2

9

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>;
  }
})
Sign up to request clarification or add additional context in comments.

3 Comments

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
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); } }
I've changed my answer so it should work for that.
1

You can do this

class Mycomponent extends React.component {
 submit(e) {
  //handle event
 }
 render() {
  return <button className={s.button} onClick={this.submit.bind(this)} />
 }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.