Pieces of paper

When you get started with React, you'll notice that data flows one way - from parent to child components.

I wanted to test out using a two-way data workflow without implementing Flux/Redux. So I built a toggle sidebar to display this behaviour through using callback functions.

Diagram of two-way data flow

In the image below, my page is the parent and the Sidebar & Main Sections are child components of this parent. As the Sidebar toggles from an open state to a closed state, I want the width of the Main Section to dynamically fill its container.

Open Sidebar

I'm including a couple of code snippets of how I achieved this. In my parent component, I created a state to track whether the sidebar was open or not.

this.state = {
    isSidebarOpen: true

Then I created a method which updates the state:

setSidebarState(isSidebarOpen) {
        isSidebarOpen: !this.state.isSidebarOpen

Here is my parent render function:

render() {
    <Sidebar isSidebarOpen={ this.state.isSidebarOpen }
              setSidebarState={ this.setSidebarState }
    <MainSection isSidebarOpen={ this.state.isSidebarOpen } />

I'm passing the callback method as a prop to the child component which will be used to communicate back to its parent when the state has changed. This will trigger other child components using that state.

To take a look at my project in full, you can find my repo here.