ReactJS call parent method
Solution 1:
To do this you pass a callback as a property down to the child from the parent.
For example:
var Parent = React.createClass({
getInitialState: function() {
return {
value: 'foo'
}
},
changeHandler: function(value) {
this.setState({
value: value
});
},
render: function() {
return (
<div>
<Child value={this.state.value} onChange={this.changeHandler} />
<span>{this.state.value}</span>
</div>
);
}
});
var Child = React.createClass({
propTypes: {
value: React.PropTypes.string,
onChange: React.PropTypes.func
},
getDefaultProps: function() {
return {
value: ''
};
},
changeHandler: function(e) {
if (typeof this.props.onChange === 'function') {
this.props.onChange(e.target.value);
}
},
render: function() {
return (
<input type="text" value={this.props.value} onChange={this.changeHandler} />
);
}
});
In the above example, Parent
calls Child
with a property of value
and onChange
. The Child
in return binds an onChange
handler to a standard <input />
element and passes the value up to the Parent
's callback if it's defined.
As a result the Parent
's changeHandler
method is called with the first argument being the string value from the <input />
field in the Child
. The result is that the Parent
's state can be updated with that value, causing the parent's <span />
element to update with the new value as you type it in the Child
's input field.
Solution 2:
2019 Update with react 16+ and ES6
Posting this since React.createClass
is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.
Parent
import React, {Component} from 'react';
import Child from './Child';
export default class Parent extends Component {
es6Function = (value) => {
console.log(value)
}
simplifiedFunction (value) {
console.log(value)
}
render () {
return (
<div>
<Child
es6Function = {this.es6Function}
simplifiedFunction = {this.simplifiedFunction}
/>
</div>
)
}
}
Child
import React, {Component} from 'react';
export default class Child extends Component {
render () {
return (
<div>
<h1 onClick= { () =>
this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
}
Simplified stateless child as ES6 constant
import React from 'react';
const Child = (props) => {
return (
<div>
<h1 onClick= { () =>
props.es6Function(<SomethingThatYouWantToPassIn>)
}
> Something</h1>
</div>
)
}
export default Child;