Skip to content

Add Routing and Navigation

Marco E edited this page Jan 24, 2022 · 1 revision
  1. "Routing" is a term for when the form of the application is affected by the URL bar.
  2. react-router determines which React component to display based on URL.
  3. Good use of routing allows a lot of information to be codified in URL.

Add React Router

React Router will add routing capabilities for our app. Add react-router-dom which is a subset of React Router that is used in the browser:

NOTE: React router is at v6 as of 2022. Many commands have changed. If you have problems refer to the official documentation https://reactrouter.com/docs/en/v6. It is still possible to use v5 with the following documentation https://v5.reactrouter.com/web/guides/quick-start.

# react-router-dom@4.3.1 (at the time of the demo)
$ npm install react-router-dom --save

NOTE: in the original version, history was also installed but it seems deprecated. The command used was npm install --save history@4.7.2. The method imported from the library was createBrowserHistory which helped React Router to determine what the object is and what it was in the past.

Update Main.jsx to import BrowserRouter and Route:

  • We also add a Navigation component. The Navigation component imports Link from react-router-dom to navigate through the app. Refer to the code project for more info.
import React from 'react';
import { Provider } from 'react-redux';
import { store } from '../store';
import { ConnectedDashboard } from './Dashboard';
import { BrowserRouter, Route, } from 'react-router-dom';
import { ConnectedNavigation } from './Navigation';

export const Main = ()=> (
    <BrowserRouter>
        <Provider store={store}>
            <div className="container mt-3">
                <ConnectedNavigation/>
                {/*<ConnectedDashboard/>*/}
                <Route
                    exact
                    path="/dashboard"
                    render={ () => (<ConnectedDashboard/>)}
                />
            </div>
        </Provider>
    </BrowserRouter>
)

Clone this wiki locally