Skip to content

React Router

Introduction

React has no opinion about routing – it’s up to you choose one!

React Router is the most popular (but there are others) - Supports hooks - https://reacttraining.com/react-router/web/api/Hooks - useHistory, useLocation, useParams, useRouteMatch

> npm install react-router-dom
> npm install @types/react-router-dom --save-dev

Router Features

  • Route
  • URL Parameters
  • Link
  • Redirects
  • 404
  • Transitions

Routing providers

Different routing providers:

  • BrowserRouter – HTML5 history api (no hashes, needs server support)
  • HashRouter – classical SPA routing, no server support needed
  • MemoryRouter – no URL at all (no deep links also) (React Native)

How to start

Wrap app entry point in router. That makes router accessible in every sub-component.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import { BrowserRouter as Router } from "react-router-dom";
import App from './App';

ReactDOM.render(
    <Router>
        <React.StrictMode>
            <App />
        </React.StrictMode>
    </Router>,
    document.getElementById('root')
);

Update App.tsx

<Route path="path to look for" component={Component to load} />

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { Route } from "react-router-dom";

const App = () => (
    <>
    <Header />
    <div className="container">
        <main role="main" className="pb-3">
            <Route exact path="/" component={Home} />
            <Route path="/GpsSessions" component={GpsSessions} />
            <Route path="/Privacy" component={Privacy} />
        </main>
    </div>
    </>
);

Exact path

1
<Route exact path="/" component={Home} />

exact – the path has to match exactly, not just the start of it

  • Generating URLs/links for clientside pageloads
  • <Link to="user/1">
  • Route path supports variables e.g. path="/user/:userId">
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<ul className="navbar-nav flex-grow-1">
    <li className="nav-item">
        <Link to="/" className="nav-link text-dark">Home</Link>
    </li>
    <li className="nav-item">
        <Link to="/Privacy/1" className="nav-link text-dark">Privacy</Link>
    </li>
    <li className="nav-item">
        <Link to="/GpsSessions" className="nav-link text-dark">Gps Sessions</Link>
    </li>
</ul>

params

Use object destructuring and useParams hook

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import React from 'react';
import { useParams } from 'react-router-dom';

interface PrivacyProps {
    message: string;
    showIt?: boolean;
}

const Privacy = ({ message, showIt = false }: PrivacyProps) => {
    let { id } = useParams();
    return (
        <h1>
            Privacy {showIt ? message : 'is disabled'} and {id}
        </h1>
    );
}

export default Privacy;

For navigation links use NavLink. NavLink accepts extra param activeClassName="active"

Switch and 404

Switch – searches through its routes and when match is found – renders it and stops.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import { Route, Switch } from "react-router-dom";

const Page404 = () => <div>404</div>;

const App = () => (
    <>
        <Header />
            <div className="container">
            <main role="main" className="pb-3">
                <Switch>
                    <Route exact path="/" component={Home} />
                    <Route path="/GpsSessions" component={GpsSessions} />
                    <Route path="/Privacy/:id" component={Privacy} />
                    <Route component={Page404}/>
                </Switch>
            </main>
        </div>
    </>
);

Redirects

Use redirect

1
2
<Navigate to=‘/GpsSessions’>
<Navigate from=‘/old-path’ to=‘/new-path’>

Render conditionaly!

Query params

Use custom hook around useLocation MDN URLSearchParams

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const useQuery = () => new URLSearchParams(useLocation().search);

const Privacy = ({ message, showIt = false }: PrivacyProps) => {
    let { id } = useParams();
    let query = useQuery();

    return (
        <h1>
            Privacy {showIt ? message : 'is disabled'} and {id} and query {query.toString()}
        </h1>
    );
}

Much more

  • Prompt – Prevent transition
  • PrivateRoute – Protected routes
  • Animated transitions
  • And many more

https://reacttraining.com/react-router/web/guides/quick-start