Passing Methods reference between Components

We have created a function in parent component and we want to use that function in child component. For this, we pass methods from parent component to child components as reference using props.

Let’s make a call to the function by clicking a paragraph in one of the child component.

Persons.js

import React from 'react';

const Person = (props) => {
    return (
        <div>
         My name is {props.name} and I stay in {props.location}! {props.children}.
        </div>
    );
}

export default Person;


App.js: The method gets called when you click on the first paragraph.

import React from 'react';
import Person from './Person/Person';

class App extends React.Component {
  state = {
      person:[
        {name: "Paul", location: "New York"},
        {name: "David", location: "Atlanta"},
        {name: "Raj", location: "London"}
      ],
      otherDetails: "I am working as Software Developer"
  }
  clickHandler = () => {
    this.setState({
      person:[
        {name: "Duke", location: "New York"},
        {name: "David", location: "Atlanta"},
        {name: "Raj", location: "Delhi"},
      ]
    })
  }
  render(){
    return (
      <div>
        <Person name={this.state.person[0].name} location={this.state.person[0].location} paraClick = {this.clickHandler}/>
        <Person name={this.state.person[1].name} location={this.state.person[1].location} >{this.state.otherDetails}</Person>
        <Person name={this.state.person[2].name} location={this.state.person[2].location} />
      </div>
    );
  } 
}
export default App;

Output before clicking the first paragraph

Output after clicking the first paragraph

There will be no changes if you click other paragraphs.

Related Articles
Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started