How to pass function as props to another component in Reactjs


Every Reactjs components can communicate each other. Lets make a component talk with another. We can pass component member as props /property to another component, so that it can return a response

Here is a simple class component Guest with a class property greet, which is responsible for updating the component UI.

class Guest extends Component {
constructor(props) {
  super(props);
  this.state = {
    greetTxt: "",
  };

}


//As a class property
greet=(greet)=> {
  this.setState({ greetTxt: greet });
}
render() {
  return (
    <div>
      <h4>{this.props.name}</h4>
      {this.state.greetTxt}

<Host
        name="SPC International"
        country="Australia"
        greetGuest={this.greet}
      />

    </div>
  );
}

and in the Host component , it uses props to communicate with the function in Guest component. As a result the UI update when the Host event triggered.

Here is the Host Component declaration

import React from "react";

function Host(props) {
return (
  <div>
      {props.name}<p> </p>
    <button onClick={()=>props.greetGuest(`Welcome to ${props.country}`)}>Greet</button>
  </div>
);
}

export default Host;

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

One thought on “How to pass function as props to another component in Reactjs”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.