Ranmal Mendis
Ranmal Mendis

Reputation: 141

How to Pass an Event Handler as a prop in React?

I have two js files. 1.Talker.js 2.Button.js

Talker.js

    import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from './Button';

class Talker extends React.Component {
  talk() {
    let speech = '';
    for (let i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  }

  render() {
    return <Button talk={this.talk} />;
  }
}

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);

Button.js

import React from 'react';

export class Button extends React.Component {
  render() {
    return (
      <button>
        Click me!
      </button>
    );
  }
}

I wanted to pass the 'talk' method to 'Button' .But when i change the code

return <Button talk={this.talk} />;

in Talker class to

 return <Button talk={talk} />;

it also working fine.What is the use of 'this' key word here?Is it neccessary? What is the difference happen when i use the second piece of code?

Upvotes: 4

Views: 7868

Answers (3)

Colin Ricardo
Colin Ricardo

Reputation: 17239

You're not using the this.props.talk in the Button component, so it doesn't do anything when clicked, and you also don't get an error.

You need to do two things:

1.) Add an onClick handler in your Button component.

<button onClick={this.props.talk}>click me</button>

2.) In your Talker component, make sure you're using this when you pass the prop. If you try and do talk={talk} you'll get an error when you click the button, as talk is undefined. What you're looking for is: talk={this.talk} to refer to the function talk() you defined in the Talker component.

Working example here.

Upvotes: 3

apaatsio
apaatsio

Reputation: 3793

Are you sure <Button talk={talk} />; works? Because talk is undefined there so I'm a bit confused. It shouldn't work.

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138235

Cause Button does never call talk. If you would accept it as a button property, e.g.:

 export class Button extends React.Component { 
   render() { 
      return <button onClick={this.props.talk} >Click me!</button>;
   }
 }

Then passing talk will fail, as talk is undefined and that cant be called. So no, it is not working fine. Using this to refer to the context is mandatory.

Upvotes: 3

Related Questions