Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
- Installation
- Components
- BrowserRouter
- Link
- Route
- Access the location data inside a rendered component
- Programmatically change the route
- Match multiple paths
- Inline rendering
- Match dynamic route parameter
React Router is the de-facto React routing library, and it’s one of the most popular projects built on top of React.
React at its core is a very simple library, and it does not dictate anything about routing.
Routing in a Single Page Application is the way to introduce some features to navigating the app through links, which are expected in normal web applications:
- The browser should change the URL when you navigate to a different screen
- Deep linking should work: if you point the browser to a URL, the application should reconstruct the same view that was presented when the URL was generated.
- The browser back (and forward) button should work like expected.
Routing links together your application navigation with the navigation features offered by the browser: the address bar and the navigation buttons.
React Router offers a way to write your code so that it will show certain components of your app only if the route matches what you define.
Installation
With npm:
npm install react-router-dom
Components
The 3 components you will interact the most when working with React Router are:
BrowserRouter
, usually aliased asRouter
Link
Route
BrowserRouter
wraps all your Route components.
Link
components are used to generate links to your routes
Route
components are responsible for showing - or hiding - the components they contain.
BrowserRouter
Here’s a simple example of the BrowserRouter component. You import it from react-router-dom, and you use it to wrap all your app:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router } from 'react-router-dom'
ReactDOM.render(
<Router>
<div>{/* ... */}</div>
</Router>,
document.getElementById('app')
)
A BrowserRouter component can only have one child element, so we wrap all we’re going to add in a div
element.
Link
The Link component is used to trigger new routes. You import it from react-router-dom
, and you can add the Link components to point at different routes, with the to
attribute:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Link } from 'react-router-dom'
ReactDOM.render(
<Router>
<div>
<aside>
<Link to="/dashboard">Dashboard</Link>
<Link to="/about">About</Link>
</aside>
{/* ... */}
</div>
</Router>,
document.getElementById('app')
)
Route
Now let’s add the Route component in the above snippet to make things actually work as we want:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Link, Route } from 'react-router-dom'
const Dashboard = () => (
<div>
<h2>Dashboard</h2>
...
</div>
)
const About = () => (
<div>
<h2>About</h2>
...
</div>
)
ReactDOM.render(
<Router>
<div>
<aside>
<Link to="/">Dashboard</Link>
<Link to="/about">About</Link>
</aside>
<main>
<Route exact path="/" component={Dashboard} />
<Route path="/about" component={About} />
</main>
</div>
</Router>,
document.getElementById('app')
)
Check this example on Glitch: https://glitch.com/edit/#!/flaviocopes-react-router-v4/
When the route matches /
, the application shows the Dashboard component.
When the route is changed by clicking the “About” link to /about
, the Dashboard component is removed and the About component is inserted in the DOM.
Notice the exact
attribute. Without this, path="/"
would also match /about
, since /
is contained in the route.
Access the location data inside a rendered component
Inside the rendered component we can see which route we are on, using the useLocation
hook:
import { useLocation } from 'react-router-dom'
//...
function Post() {
const location = useLocation()
console.log(location.pathname) // '/'
}
Programmatically change the route
Inside the rendered component you can programmatically change the route using the useHistory
hook:
import { useHistory } from 'react-router-dom'
//...
function Post() {
const history = useHistory()
history.push('/post/new')
}
Match multiple paths
You can have a route respond to multiple paths using a regex, because path
can be a regular expressions string:
<Route path="/(about|who)/" component={Dashboard} />
Inline rendering
Instead of specifying a component
property on Route
, you can also set a render
prop:
<Route
path="/(about|who)/"
render={() => (
<div>
<h2>About</h2>
...
</div>
)}
/>
Match dynamic route parameter
See how to get data from a dynamic React Router route.
Download my free React Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More react tutorials:
- A React simple app example: fetch GitHub users information via API
- Build a simple counter with React
- VS Code setup for React development
- How to pass props to a child component via React Router
- Create an app with Electron and React
- Tutorial: create a Spreadsheet using React
- The roadmap to learn React
- Learn how to use Redux
- Getting started with JSX
- Styled Components
- Introduction to Redux Saga
- Introduction to React Router
- Introduction to React
- React Components
- The Virtual DOM
- React Events
- The React State
- React Props
- The React Fragment
- The React Context API
- React PropTypes
- React concepts: declarative
- React: How to show a different component on click
- How to loop inside React JSX
- Props vs State in React
- Should you use jQuery or React?
- How much JavaScript you need to know to use React?
- Introduction to Gatsby
- How to reference a DOM element in React
- Unidirectional Data Flow in React
- React Higher Order Components
- React Lifecycle Events
- React Concept: Immutability
- React Concept: Purity
- Introduction to React Hooks
- Introduction to create-react-app
- React Concept: Composition
- React: Presentational vs Container Components
- Code Splitting in React
- Server Side Rendering with React
- How to install React
- CSS in React
- Using SASS in React
- Handling Forms in React
- React StrictMode
- React Portals
- React Render Props
- Testing React components
- How to pass a parameter to event handlers in React
- How to handle errors in React
- How to return multiple elements in JSX
- Conditional rendering in React
- React, how to transfer props to child components
- How to get the value of an input element in React
- How to use the useState React hook
- How to use the useCallback React hook
- How to use the useEffect React hook
- How to use the useMemo React hook
- How to use the useRef React hook
- How to use the useContext React hook
- How to use the useReducer React hook
- How to connect your React app to a backend on the same origin
- The Reach Router Tutorial
- How to use the React Developer Tools
- How to learn React
- How to debug a React application
- How to render HTML in React
- How to fix the `dangerouslySetInnerHTML` did not match error in React
- How I fixed an issue with a React login form state and Browser autofill
- How to configure HTTPS in a React app on localhost
- How to fix the "cannot update a component while rendering a different component" error in React
- Can I use React hooks inside a conditional?
- Using useState with an object: how to update
- How to move around blocks of code with React and Tailwind
- React, focus an item in React when added to the DOM
- React, edit text on doubleclick
- React Router, how to get data from a dynamic route
- React Router, why useLocation and useHistory might return undefined
- The easy-peasy React state management library