5.2 React Router
# What is client-side routing?
Traditional application page routing would mean loading a whole new HTML page with all of its assets (JavaScript, CSS, images, etc) from the server.
Client-side routing is controlled by your JavaScript application. It more efficiently uses AJAX to fetch any additional required assets (lazy-loading) while using JavaScript to update the DOM.
# Third party libraries
Routing is not a core component of the React UI library. There are several third-party modules that you can use with React. By far, the most popular is called react-router
. It has three component libraries: react-router-dom
, react-router-native
, and the core react-router
that is shared by both of the other two.
# Usage
The official documentation is quite good. There is no need to reinvent it here. The core components that you will need are:
I suggest that you start with the Primary Components Guide.
# Demo Example
- Create a new React project with
create-react-app
- Add
react-router-dom
to the project usingyarn
yarn add react-router-dom
- Clear out the content of the default
<App />
component and its CSS file. - Create three stateless function components called: Home, About, and Contact
- Import the BrowserRouter component and make it the top / parent component in the JSX for
<App />
.
import { BrowserRouter as Router } from 'react-router-dom'
// ... other code ...
return (
<Router>
<div className='App'></div>
</Router>
)
- Create a
<nav>
area at the top of the<App />
component that has links to the three other view components.
<NavLink to="/">Home</NavLink>
<NavLink to="/about">About</NavLink>
<NavLink to="/contact">Contact</NavLink>
- Below the nav-bar, add the
<Route>
matcher components to display the various pages / views.
<Route path="/"><Home /></Route>
<Route path="/about"><About /></Route>
<Route path="/contact"><Contact /></Route>
- Add
<Switch>
component as a wrapper around the<Route />
components
# Dynamic URLs
Often we need to get some route parameters from the URL.
- Add another route with a path of
/movie/:id
- Add
<Movie />
component
const Movie = () => {
const { id } = useParams()
return <h1>Movie id:{id}</h1>
}
# Practice Exercise
Create a new React app that will fetch a list of Star Wars films from the swapi.dev
API.
- Display a list of the movie titles on the left side of the page.
- Make them clickable links.
- When the title of a movie is clicked, display the full movie details on the right side of the page.
# Solution
You can find the complete solution files that we reviewed in class in this GitHub repo.
Look for the embedded comments in the code for reminders.