pass functions as props react code example
Example 1: pass props in react
const expression = 'Happy';
<Greeting statement='Hello' expression={expression}/>
class Greeting extends Component {
render() {
return <h1>{this.props.statement} I am feeling {this.props.expression} today!</h1>;
}
}
Example 2: pass function with parameter as prop
class SomeComponent extends Component{
constructor(props){
super(props);
this.myFunction = this.myFunction.bind(this);
}
myFunction(param){
console.log('do something: ', param);
}
render(){
return (<div><ChildComponent1 myFunction={this.myFunction}/></div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 myFunction={this.props.myFunction}/></div>)
}
}
class ChildComponent2{
render(){
return (<Button onClick={()=>this.props.myFunction(param)}>SomeButton</Button>)
}
}
Example 3: react pass parameter to component
import React, { Component } from 'react'; class App extends Component { render() { return ( <div> <Greeting /> </div> ); }} class Greeting extends Component { render() { const greeting = 'Welcome to React'; return <h1>{greeting}</h1>; }} export default App;