21 February 2020

Passing Method References Between Components Example in React

  • Create Components folder under src folder
  • Add PassingMethodReferencesBetweenComponent.js file and add below Code
import React,{Componentfrom 'react';
import Person from './Person';

class  PassingMethodReferencesBetweenComponent extends Component {
  state={
    Person:[
      {name:'adi',age:29},
      {name:'balu',age:30},
      {name:'krishna',age:28}
    ],
    otherState:'some other value'
  }
switchNameHandler=()=>{
this.setState({Person:[
    {name:'jc adi',age:29},
    {name:'balu',age:30},
    {name:'krishna',age:28}
  ]})
}

  render(){
  return (
    <div>
        <p>Passing Method References Between Components Example</p>
      <Person 
      name={this.state.Person[0].name} 
      age={this.state.Person[0].age}/>
      <Person 
      name={this.state.Person[1].name} 
      age={this.state.Person[1].age}
      click={this.switchNameHandler}/>
      <Person 
      name={this.state.Person[2].name} 
      age={this.state.Person[2].age}/>
    </div>
  );
  }
}

export default PassingMethodReferencesBetweenComponent;
  • Add Person.js file and add below Code
import React from 'react';

const person =(props)=>{
    return(
        <div>
        <p onClick={props.click}>I'm a {props.name} and i am {props.age} years old!</p>
        <p>{props.children}</p>
        </div>
    );
}
export default person;
  • Open App.js file and update code as below
import React from 'react';
import './App.css';
import PassingMethodReferencesBetweenComponent from './Components/PassingMethodReferencesBetweenComponent'

function App() {
  return (
    <div className="App">
     <PassingMethodReferencesBetweenComponent/>
    </div>
  );
}

export default App;
Output:


No comments:

Post a Comment