4Geeks logo
4Geeks logo

Bootcamps

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Academy

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Full-Stack Software Developer - 16w

Data Science and Machine Learning - 16 wks

Search from all Lessons


LoginGet Started
← Back to Lessons

Weekly Coding Challenge

Every week, we pick a real-life project to build your portfolio and get ready for a job. All projects are built with ChatGPT as co-pilot!

Start the Challenge

Podcast: Code Sets You Free

A tech-culture podcast where you learn to fight the enemies that blocks your way to become a successful professional in tech.

Listen the podcast
Edit on Github

Routing our Views with React Router

What is React Router?
Anchors <a> are now a Problem

What is React Router?

React Router is a JS library available through NPM that helps mainly with 2 problems:

  • Conditional display for React components based on the current website URL.
  • Web application navigation without having to refresh.

This is how you would install React Router in your project:

1$ npm install --save react-router

Why do I need this?

Stop reading if you are not building entire applications using React, you don’t need React-Router for single-page applications or small components.

For the rest of us building real web applications, we need to connect several views (React components) into one big application. That process is called "routing."

For example, we need the following application URLs to match the following components:

react router URL and component example

Defining your Application Routes

What pages/views do you want your app to have? You can always start with the basic ones:

  • Home: What your public users view when they land in yourdomain.com
  • Login/Signup/Forgot: A login and signup form and the password reminder form.
  • Private: What your private users view right after they log in.

The rest of the pages depend on your application and on how you want your users to navigate through your site.

react router ecommerce example

Mapping your Views to URLs

This is the sitemap for any typical e-commerce website:

react router mapping views

Coding your Application Routes

Once you have finished mapping your application views with URLs, you can start coding everything, and that is when React-Router comes in!

The best practice is always to create one component called <Layout /> which will take care of routing the users to the specific views they should see, depending on each of the particular URLs.

This is an example of the same e-commerce sitemap but now using React Router v6:

1// This component <Layout /> will take care of routing the URLs with all my application views 2 3export const Layout = () => { 4 return ( 5 <div> 6 <BrowserRouter> 7 <Routes> 8 <Route element={<Home />} path="/" /> 9 <Route element={<Demo />} path="/demo" /> 10 <Route element={<Single />} path="/single/:theid" /> 11 <Route element={<h1>Not found!</h1>} /> 12 </Routes> 13 </BrowserRouter> 14 </div> 15 ); 16}

There are 3 components to understand here:

  • <BrowserRouter>: Every time you open a new BrowserRouter tag, you are basically telling React that everything that is inside must be conditionally rendered, based on particular (URLs).
  • <Routes>: Works similar to the switch statement in JavaScript but for Routes... It tells React that only the first <Route> that matches the URL will be displayed.
  • <Route>: It’s the way of React-Router to map routes with components, for example:
1<Route element={<Signup />} path="/sign-up" />

This route is telling React that when the URL matches "sign-up", the component Signup should be displayed.

Anchors <a> are now a Problem

Anchors take users to other websites or URLs, and that is amazing for simple plain HTML+JS, but now we DON’T want our users to be taken to other websites or URLs. We want them to remain in the same tab but be able to load the next page without having to refresh. We have two possible approaches of doing that:

1. Using a <Link> tag:

React Router created a component that we can use instead of <a>:

1<Link to="/login">Take me to login</Link>

2. Using history.push('new/url/here'):

React Router always passes to each view a prop called "history", which contains a lot of useful information to use when routing users. One of its many useful utilities is the "push" function, which basically redirects the user to a given path.

You can access the history object by using the useNavigate hook like this:

1import { useNavigate } from "react-router-dom"; 2 3// Inside the component, you declare the useNavigate this way: 4const navigate = useNavigate();

Then, anywhere in any of your components, you can programmatically redirect users to another URL like this:

1<button onClick={() => navigate("/login")}>Take me to login</button>

Live Example:

Here is a live example using everything that we've learned in this reading. Please click and play to understand it, learn it and replicate it:

Click here to open demo in a new window