React Router DOM is the ultimate solution for defining routing in React.js. This article covers the creation of routes, links to switch pages, passing route parameters, programmatic navigation, redirecting to other pages, diverting to a 404 page, guarding routes and establishing the project.
Along with theory, we will understand this topic with the help of an example for better clarity.
Let us start with article flow.
What is routing in react.js?
Routing is an essential component of web application creation because it enables users to travel around different sections of the app by clicking on links or typing URLs in the address bar.
It works by mapping URLs to different pages and components within a web-based platform, allowing people to swiftly and conveniently access the information they need.
Consequently, routing is essential for constructing a successful web application that provides consumers with an effortless navigation experience.
Setting up the project: Install React Router DOM
You’ll need a project with package management like npm or yarn and a fundamental understanding of React to get started. Once you have that, run the following command to install React Router:
npm install react-router-dom
Or
yarn add react-router-dom
Setting up the Router
In React Router DOM v6, the way of creating routes and handling redirects has slightly changed.
Instead of using the `<Switch>` component and `<Redirect>` component, we use the `<Routes>` component and `<Navigate>` component.
We’ll make a new Routes
component to display our Routes to configure the router. Two routes shown in the example below are `/`
and
`/about
`.
import { Routes, Route } from 'react-router-dom'
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
)
}
In this example, the `Home` component will be displayed when the user accesses `/`
, and the
`About` component will be displayed when a user access `/about
`.
Rendering routes
In addition to the `Routes`
component, React Router also provides a
`Route` component, which is used to render a particular component when a route matches the current URL.
Please note the difference is ‘s’ in the two “Route” above.
When the URL does not match one of the defined routes, you can use the `Route`
component to render a `NotFound` component:
For example,
import {Routes, Route} from 'react-router-dom'
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
)
}
In this case, the `NotFound` component is displayed whenever the user accesses a URL that does not match `/ ` or `/about`.
Using Links to switch pages
It is necessary to be aware that when users click on a `Link` component, their browser’s URL will change without reloading the whole page.
In other words, the use of the `Link` component will change the page URL in an instant.
This process is called client-side routing, and it gives an uninterrupted user experience since the program can renew itself without necessitating a page refresh.
For example, you can use the `Link` component to create a link that navigates to the `About` page:
import {Link} from ' react-router-dom'
function App() {
return (
<div>
<Link to="/about">About</Link>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
</div>
)
}
In this example, on clicking the “About” link, the user is redirected to the ‘/about’ route, where they can view the `About
` component.
Passing Route Parameters
You can render dynamic content using React Router’s ability to send parameters to your routes.
For example, a specific item ID can be passed and then used to obtain data and present it on the page. The way to incorporate parameters into a route is by putting them in the path preceded by a colon (:).
For example, if an ID parameter is supposed to be passed to the `/about`
route, you would use the following path:
`/about/:id
`.
The `useParams`
hook is used to access the passed parameters.
In the About
component, for instance, you might use this code to gain access to the ID parameter:
import { useParams } from 'react-router-dom'
function About() {
const { id } = useParams()
return <div>About {id}</div>
}
Navigating programmatically
Sometimes, you may need to navigate to a different route programmatically without the user clicking a link. React Router provides the `Navigate` component for this purpose.
For example, you can use the `Navigate` component to navigate to the `About` page when a button is clicked:
import {Navigate} from 'react-router-dom'
function Home() {
const handleClick = () => {
return <Navigate to="/about" />
}
return (
<div>
<button onClick={handleClick}>Go to About</button>
</div>
)
}
Redirecting to Another Page
React Router also allows you to redirect the user to a different route. You could refer users to the login page, for instance, if they attempt to access a protected route while not logged in.
Use the `Navigate` component with the `replace` prop set to true to send the user to a different page.
import {Navigate} from 'react-router-dom'
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false)
return (
<div>
{!isLoggedIn && <Navigate to="/login" replace={true} />}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/login" element={<Login />} />
</Routes>
</div>
)
}
When users visit any route other than `/login` in this example, they are sent to the `/login` route if they are not logged in.
Redirecting to a 404 page
You can lead the user to a 404 page if they attempt to access an invalid route. The `*` wildcard character is used in the path to achieving this.
import {Navigate} from 'react-router-dom'
function App() {
return (
<div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
</div>
)
}
This example will redirect the user to the `NotFound` page if they attempt to access a route that is not `/`or `/about`
Guarding routes
You may restrict access to particular routes depending on certain factors, such as whether the user is signed in.
If necessary, the user is redirected to a different path using the `useEffect
` hook to check for these conditions.
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
function Home() {
const navigate = useNavigate()
const [isLoggedIn, setIsLoggedIn] = useState(false)
useEffect(() => {
if (!isLoggedIn) {
navigate('/login')
}
}, [isLoggedIn, navigate])
return <div>Home</div>
}
In this example, the `Home
` component will only display if the user is signed in. They are redirected to the `/login` route if they are not logged in.
Router Hooks
React Router provides several hooks that allow us to access the router’s state and perform navigation.
useNavigate
The `useNavigate
` hook allows you to navigate to a different route programmatically.
useLocation
The `useLocation
` hook allows you to access the current location, including the pathname and search parameters.
useMatch
The `useMatch
` hook allows you to check if the current location matches a specific route.
useParams
The `useParams
` hook allows you to access the parameters passed to a route.
Final Thoughts
React Router is an essential tool for building client-side applications with React. It allows us to handle routing declaratively and efficiently by breaking our application into smaller, reusable components.
With the help of hooks and other advanced features, we can easily handle navigation, redirects, and route guards in our application.
This article covers the basics of React Router. It is equipped with many more complex functions and capabilities. Therefore, while developing applications with React Router, you are advised to explore its documentation and other resources to learn more about its abilities and best practices.
Probable Errors and Solutions:
While working with ‘react-router-dom’ you may get few errors. I have mentioned some of them with their solutions. Hope it helps.
Error:'useHistory'
is not exported from ‘react-router-dom’
Or,
export ‘useHistory’ (imported as ‘useHistory’) was not found in ‘react-router-dom’
Solution:
import { useNavigate } from 'react-router-dom'; //instead of useHistory import useNavigate
const navigate = useNavigate(); //declare a constant navigate
navigate('/home'); //redirect to the ‘path name’ used ‘/home’ here.
Error:'Switch'
is not exported from 'react-router-dom'
Or
export ‘Switch’ (imported as ‘Switch’) was not found in ‘react-router-dom’
Solution:
import { Routes } from 'react-router-dom'; //instead of Switch import Routes
// instead of Switch use Routes } /> // instead of component use element
Error:'Redirect'
is not exported from 'react-router-dom'
Or
export ‘Redirect’ (imported as ‘Redirect’) was not found in ‘react-router-dom’
Solution:
import { Navigate } from 'react-router-dom' //instead of Redirect import Navigate
: }/> // instead of Redirect to use Navigate to