Step 4
Adding a router
Modern applications don't just have 1 URL, they have multiple routes that you can go to. React is a library, not a framework, so if we want things like a router, then we have to use a 3rd party library, like React Router. Let's map our Books container to a URL.
$ yarn add react-router-dom
$ yarn add -D @types/react-router-dom
If you do not have Yarn:
$ npm i -S react-router-dom
$ npm i -D @types/react-router-dom
React router will intercept all requests to our app and render the correct component based on the route. In order to use it, we need to wrap our App in a router component
src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
This isn't particularly useful, so let's add a route
src/App.tsx
import React, { Component } from 'react';
import './App.css';
import BooksPage from './containers/Books';
import { Switch, Route } from 'react-router-dom';
class App extends Component {
render() {
return (
<div className="App App-header">
<Switch>
<Route exact path="/books" component={BooksPage} />
</Switch>
</div>
);
}
}
export default App;
We are wrapping our route in a Switch component, which acts kind of like a switch statement and only renders the component that matches the path. We add "exact" to our route because we don't want to render other components that might also match the "/books" path on accident.
When you go to http://localhost:3000, you won't see anything. If you go to http://localhost:3000/books then you will see the books page. There is no default page, so let's add a Home page.
src/containers/Home.tsx
import React, { Component } from 'react';
export default class HomePage extends Component {
render() {
return <div>The home page</div>;
}
}
src/App.tsx
import React, { Component } from 'react';
import './App.css';
import BooksPage from './containers/Books';
import { Switch, Route } from 'react-router-dom';
import HomePage from './containers/Home';
class App extends Component {
render() {
return (
<div className="App App-header">
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/books" component={BooksPage} />
</Switch>
</div>
);
}
}
export default App;
Last updated
Was this helpful?