Child Events

When we need to update the state of the parent component from its child, we can create an event handler (updateState) in the parent component and pass it as a prop (updateStateProp) to the child component where we can just call it.

App.jsx

import React from ‘react’;

class App extends React.Component {

constructor(props) {

super(props);

this.state = {

data: ‘Initial data…’

}

this.updateState = this.updateState.bind(this);

};

updateState() {

this.setState({data: ‘Data updated from the child component…’})

}

render() {

return (

<div>

<Content myDataProp = {this.state.data}

updateStateProp = {this.updateState}></Content>

</div>

);

}

}

class Content extends React.Component {

render() {

return (

<div>

<button onClick = {this.props.updateStateProp}>CLICK</button>

<h3>{this.props.myDataProp}</h3>

</div>

);

}

}

export default App;

main.js

import React from ‘react’;

import ReactDOM from ‘react-dom’;

import App from ‘./App.jsx’;

ReactDOM.render(<App/>, document.getElementById(‘app’));

Share this post
[social_warfare]
Passing Arguments to Event Handlers
SyntheticEvent

Get industry recognized certification – Contact us

keyboard_arrow_up