0

I know I can bind this in a couple of different ways in react like these:

<button onClick={this.onSelect.bind(this, data)}>Button</button>

or

<button onClick={() => this.onSelect(data)}>Button</button>

or

constructor(props) {
   super(props);
   this.onSelect= this.onSelect.bind(this)
}
<button onClick={this.onSelect}>Button</button>

The problem is that I cannot send data using third option. Is there anyway to use the third option and send data as well?

Amir Shahbabaie
  • 1,352
  • 2
  • 14
  • 33
  • You can check https://stackoverflow.com/questions/45053622/how-to-avoid-bind-or-inline-arrow-functions-inside-render-method/45053753#45053753 – Shubham Khatri Jan 09 '19 at 08:08

2 Answers2

0

class App extends React.Component {
  constructor(props) {
    super(props);
    this.onSelect = this.onSelect.bind(this);
  }

  onSelect(e) {
    alert(e);
  }
  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <button onClick={event => this.onSelect(event)}>Button</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

You can use ES6 Arrow Function to send data here, it is called anonymous function calling:

constructor(props) {
   super(props);
   this.onSelect= this.onSelect.bind(this)
}
<button onClick={(event) => this.onSelect(event)}>Button</button>

Like this.

Harish Soni
  • 1,796
  • 12
  • 27
0

With the new arrow function brought by the ES6 syntax, you can forget about bind. An arrow function will automatically bind to it's class context. Making your onSelect an arrow function will solve your problem.

To send your data, you can preconfigure your function to receive 2 sets of parameters, the first one being your data, and the second being the click event :

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { msg: '' }
  }

  onSelect = msg => event => {
    this.setState({ msg })
  }
  
  render() {
    const { msg } = this.state

    return (
      <div className="App">
        <h3>{msg ? 'Yay, data : ' + msg : 'Click it !'}</h3>
        <button onClick={this.onSelect('I sent data !')}>Button</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Treycos
  • 7,373
  • 3
  • 24
  • 47