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;
One thought on “How to pass function as props to another component in Reactjs”