REACT PASSING METHODS REFERENCE BETWEEN COMPONENTS

Example

import React from 'react';const person = (props ) => {return (//click is the name of the property  defined in App.js (line 43)<div><p onClick={props.click}>I'm {props.name} and I am {props.age}!</p><p>{props.children}</p></div>)};export default person;
import React, { Component } from 'react';import './App.css';import Person from './Person/Person';class App extends Component {state = {persons: [{name: "Ali Bener", age: 43 },{name: "Arslan Eksi", age: 36 },{name: "Levent Mergen", age: 74 }],otherState: ' some other value'}switchHandler = (newName) => {this.setState({persons : [{name: newName, age: 49 },{name: "Ceren Ates", age: 40 },{name: "Nevriye Yilmaz", age: 40 }]})}render() {return (<div className="App"><h1> LEGENDS LIST </h1><p>This is really working </p><button onClick={this.switchHandler.bind(this, 'Maximillian')}> Switch Name</button><Person
name={this.state.persons[0].name}
age={this.state.persons[0].age}/><Personname={this.state.persons[1].name}age={this.state.persons[1].age}click={this.switchHandler.bind(this, 'Max!')} >My Hobbies: Volleyball</Person><Personname ={this.state.persons[2].name}age={this.state.persons[2].age}/></div>);}}export default App;

Using arrow function onClick

import React, { Component } from 'react';import './App.css';import Person from './Person/Person';class App extends Component {state = {persons: [{name: "Ali Bener", age: 43 },{name: "Arslan Eksi", age: 36 },{name: "Levent Mergen", age: 74 }],otherState: ' some other value'}switchHandler = (newName) => {this.setState({persons : [{name: newName, age: 49 },{name: "Ceren Ates", age: 40 },{name: "Nevriye Yilmaz", age: 40 }]})}render() {return (<div className="App"><h1> LEGENDS LIST </h1><p>This is really working </p><button onClick={ () =>  this.switchHandler('Maximillian!!')}> Switch Name</button><Personname={this.state.persons[0].name}age={this.state.persons[0].age}/><Personname={this.state.persons[1].name}age={this.state.persons[1].age}click={this.switchHandler.bind(this, 'Max!')} >My Hobbies: Voleyball</Person><Personname ={this.state.persons[2].name}age={this.state.persons[2].age}/></div>);}}export default App;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soner Mezgitci

Soner Mezgitci

31 Followers

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux