React

Getting Started with React Router

PRO
Outline

This tutorial is a part of the "Build a Real World App with React & Redux" tutorial series.

So far you've scaffolded out a single view that displays the global feed. It's a good start, but this site's going to need several more views, so let's plug in react-router to make it happen.

What is React Router?

React Router is a complete routing library for React. It keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. -React Router docs

Refactor Store

Before we can get rolling with React Router, our index.js file is getting bloated. To fix this, let's refactor the redux store out into a store.js file.

Be sure to export store :)

Remove the following code from index.js and place into a new file called store.js

src/store.js

import { applyMiddleware, createStore } from 'redux';
import { promiseMiddleware } from './middleware';

const defaultState = {
  appName: 'conduit',
  articles: null
};
const reducer = function(state = defaultState, action) {
  switch (action.type) {
    case 'HOME_PAGE_LOADED':
      return { ...state, articles: action.payload.articles };
  }
  return state;
};

const middleware = applyMiddleware(promiseMiddleware);

const store = createStore(reducer, middleware);

export default store;

And import this file in index.js. Now index.js should look like this:

Ensure that your index.js file was updated properly

src/index.js

import ReactDOM from 'react-dom';
import React from 'react';
- import { applyMiddleware, createStore } from 'redux'; 
- import { promiseMiddleware } from './middleware'; 
+ import store from './store';

- const defaultState = { 
-    appName: 'conduit',
-    articles: null 
- };


- const reducer = function(state = defaultState, action) {
-   switch(action.type) {
-       case 'HOME_PAGE_LOADED':
-           return { ...state, articles: action.payload.articles };
-   }
-   return state; 
- };

- const store = createStore(reducer, applyMiddleware(promiseMiddleware)); 

ReactDOM.render((
    <Provider store={store}>
      <App />
    </Provider> 
), document.getElementById('root'));

Looking good! Let's get to work setting up the routing structure.

 

I finished! On to the next chapter