Mosh React tutorial (part 5)

to run: npm install, npm start
download source

Multiple Components in Sync

Under components, create a NavBar component.
Make it a basic component with a render and return empty JSX:

Go to getBootstrap, search for NavBar.

Locate a navbar you like and copy the HTML into our NavBar’s JSX.

Change ‘class’ to ‘className’.

Then import this NavBar into App.js to be used.

Finally, update our index.js to use App.js:


Now let’s look at our component tree. There’s no parent child relationship between Counters component and NavBar component.
Look at the diagram. How can we display total number of counters in our NavBar? In situations like this where there is no parent child relationships and you want to keep them in sync.

To solve this, we lift state of Counters component up into App, so that it can pass it to all its children.

Lifting State Up

First, we pull everything out from Counters, and put it in App

App.js

Since we brought the state object here, we can safely put handleIncrement and handleDelete here as well.
We pass in the Counters array to Counters component. In Counters component, we loop through that array, and use props to pass data down into each individual Component.

Notice that Counters have props onReset, onIncrement, and onDelete. These are callback functions that bubble back up to manipulate our parent array.

The callback onReset is passed to Counters to reset everything. The onIncrement and onDelete are passed into individual Counter components. A Counter component passes the component ID back up for us to increase or delete.

counters.jsx

Here in Counters component, we receive the counters array from App via props.
We then loop through each item in the array and pass associated data down to a Counter component.
We basically bubble events upward from Component. And then have App take care of them.

counter.jsx

Here is where we apply a lot of UI via css. Notice we do so by looking at the props object passed down from parent.
We use all the data passed down from the parent in order to draw and display what we want.

This is where we also receive events, and then send it up to our parent by calling function references on the props object.

In order to show that we have all the counters information, we display the # of counters with more than 0 value up in our NavBar: