Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add two onClick functions in React [duplicate]

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)}}>
like image 328
bluegen1e Avatar asked Sep 14 '16 20:09

bluegen1e


People also ask

How do you add multiple functions to onClick React?

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.

Can I trigger two functions onClick?

Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.

How do you beat two props onClick in React?

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.

How do you duplicate components in React?

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.


2 Answers

You can do this

class Mycomponent extends React.component {
 submit(e) {
  //handle event
 }
 render() {
  return <button className={s.button} onClick={this.submit.bind(this)} />
 }
}
like image 21
Pranesh Ravi Avatar answered Sep 19 '22 20:09

Pranesh Ravi


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>;
  }
})
like image 189
Buck Shlegeris Avatar answered Sep 18 '22 20:09

Buck Shlegeris