Lifting Up State in ReactJS

For the past week I’ve been teaching myself ReactJS through Codecademy and the Official ReactJS tutorial at reactjs.org. At the moment I’m…

Lifting Up State in ReactJS

For the past week I’ve been teaching myself ReactJS through Codecademy and the Official ReactJS tutorial at reactjs.org. At the moment I’m working on building a prototype for a project that I wish to build using React, but the process is slow as I’m still not used to “thinking in React.” So for my own personal reference, I would like to publish some example code demonstrating how to lift up state in React, and then pass this data back down to sibling components. In React it seems that keeping state in a top level parent component seems to be the way to go, this way you can pass the data back down to all of the children components. In the following example, <H1/>, <H2/>, and <H3/> are all sibling components and children of <App/>. So we are going to lift up state from the <H3/> component back up to the parent <App/>, and then the sibling component <H2/> will be automatically updated through the wonders of React’s one way data binding:

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const BigBreakLine = () => {
return(
<div>
<br/><br/><br/><br/><br/>
</div>
);
};
class H1 extends Component {
render() {
return (
<div>
<BigBreakLine/>
<center>
<h1>Passing State In ReactJS</h1>
</center>
</div>
);
}
}
class H2 extends Component {
render() {
return(
<div>
<center>
<h2>(Sibling) Click Counter: {this.props.clickCount}</h2>
</center>
</div>
);
}
}
class H3 extends Component {
render() {
return(
<div>
<center>
<button onClick={() => this.props.onClickProp()}>Click Me</button>
</center>
</div>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
loggedIn: false,
clicks: 0
};
this.updateClickCount = this.updateClickCount.bind(this);
}
updateClickCount() {
this.setState({
clicks: this.state.clicks + 1
});
}
render() {
return (
<div className="App">
<H1/>
<H2 clickCount={this.state.clicks}/>
<H3 onClickProp={() => this.updateClickCount()}/>
</div>
);
}
}
export default App;

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();