React Router is a fully-featured client and server-side routing library for ReactJs. We will learn more about React Router and how to configure routes in the ReactJs application.

In this article, we will get to know about React router and installation of React router and configuring routes in Reactjs

Alright let's get started,


React Router


What is React Router?

1. React Router is a fully-featured client and server-side routing library for ReactJs.

2. The React Router library helps to create and navigate between different URLs that make up your web application

3. React Router also provides unique URLs for different components in the ReactJs application and makes the UI easily shareable with other users

4. If you're planning to build a medium too large scale React application,  react-router is one of the must-have packages.

Here is the link to find the latest version of React Router


How to install React Router?

You can install React Router via npm package, below is the command to install

npm i react-router-dom

Let's run the above command in our ReactJs project, you should see the react-router-dom package in your package.json file under the dependencies section.

Here is an example code of how it should look in your package.json file

"dependencies": {
"react-router-dom": "^6.2.1",
},

How to Configure routes in ReactJs Application?

1. The first step to configure Routes with react-router is, to connect the URL in the browser with our react application.

2. For that, react-router provides a component called browser router with which we need to wrap our entire application, so in index.js at the top, we should  import a component called browser router from React router and then wrap the App component with browser router
import { BrowserRouter } from 'react-router-dom'
<BrowserRouter>
<App />
</BrowserRouter>
Below is the complete index.js file for your reference,
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>

</React.StrictMode>,
document.getElementById('root')
);

3. Before we configure the routes in the App component, we need the components that need to be
rendered for the app root and slash contact in the URL.

4. So in the source folder let me create a new folder called components within this folder let me create two files
  • Welcome.js
  • Constact.js
within Welcome.js create a very simple function component that renders the text Welcome Page do the same in Contact.js so copy paste and change Welcome to Contact

Welcome.js
import React from 'react'

function Welcome() {
return <h1>Welcome Page</h1>
}

export default Welcome

Contact.js
import React from 'react'

function Contact() {
return <h1>Contact Page</h1>
}

export default Contact

5. To configure the routes for the route configuration, we need to import two components from React router. So in app.js at the top import Routes and Route from react-router-dom

in the component,  add the Routes component,  within the Routes component we defined the individual Route, using the Route component.
On the Route component, we specify two props
  • The first prop is the path that reflects the path in the URL
  • The second prop is an element that needs to be rendered when the URL matches this path

App.js
import { Routes, Route } from 'react-router-dom'
import Contact from './components/Contact'
import Welcome from './components/Welcome'

function App() {
return (
<div>
<Routes>
<Route path="/" element={<Welcome />} />
<Route path="contact" element={<Contact />} />
</Routes>
</div>
);
}

export default App;
In the browser, if you navigate to  localhost:3000/,  you can see the welcome page being rendered.
similarly, if you navigate to  localhost:3000/contact,  you can see the contact page being rendered.


How to navigate to different routes?


In our scenario, let's add a nav navbar in the app component with two links one to the Welcome page and one to the Contact page, on click of these links we should be able to navigate between the two routes.

Let's implement this in the components folder, I'm going to create a new file navbar.js within the file,  let's define a simple navbar, the navbar is the component name and for the JSX,  I am going to add the nav tag, within the nav tag, we need two clickable elements to navigate between the routes.

To navigate to another route, React router provides us with the link component.  so at the top import
Link component from react-router-dom and then within the nav tag invoke the component. The link component renders an anchor element in the dom.  So we can specify text similar to the anchor text
so welcome and the second link with text contact, but instead of the href attribute we specify the to prop, to this prop, we assign the path of the configured route, so welcome is going to be just the forward-slash and for contact 2 is going to be slash contact.

Navbar.js
import React from 'react'
import { Link } from 'react-router-dom'

export default function Navbar() {
return (
<nav>
<Link to='/'>Welcome</Link>
<Link to='/contact'>Contact</Link>

</nav>
)
}

Let's include this component in the app component wrap the JSX with fragments and include the navbar
make sure to import the component at the top.

App.js
import { Routes, Route } from 'react-router-dom'
import Navbar from './components/Navbar'
import Welcome from './components/Welcome'
import Contact from './components/Contact'


function App() {
return (
<>
<Navbar />
<Routes>
<Route path="/" element={<Welcome />} />
<Route path="contact" element={<Contact />} />
</Routes>
</>
);
}

export default App;

If we now take a look at the browser we should be able to see welcome and contact links.

we are currently at localhost port 3000 and hence we see the welcome page,  if you click on the contact link, we are navigated to slash contact, and the contact page is rendered,  click on the welcome link, we are navigated back to the root, and the welcome page is rendered.

Also if I inspect the link element, you can see it is an anchor tag with an href attribute slash and slash contact.
So this is how you can make use of the Link component for client-side navigation that is navigating within the application.

If your intention is to navigate to an external website you can use a plain old HTML anchor tag.
Now at this point, you might have one question in your mind in the route config in app.js, we have specified just contact as the path whereas in the navbar component
on the link component, we have specified slash contact. why is that?  well to be honest even if you t remove this forward slash and head back to the browser the behavior remains the same contact page welcome page. However, the behavior can change depending on the route we are currently rendering.  The link component from and that is what is called relative path and we will learn about it later.
For now, we're going to work with absolute routes but the path will begin with a forward slash
and match the same route in the route config slash contact with contact.


How to navigate to routes programmatically?


Let's assume that is the scenario and implement a button click handler where we programmatically
navigate to a different route in our application.

For our example,  onClick of a place order button on the home page, let's navigate to the order summary page.
 So in the components folder, I am going to create a new file ordersummary.js, within the file, I'm going to create a simple component that reads the text order confirmed.

OrderSummary.js
import React from 'react'

export const OrderSummary = () => {
return (
<div>
Order confirmed!
</div>
)
}

App.js

import { Component } from 'react'
import { Routes, Route } from 'react-router-dom'
import { OrderSummary } from './components/OrderSummary';

import Welcome from './components/Welcome'

function App() {
return (
<Routes>
<Route path="/" element={Welcome} />
<Route path="contact" element={Component} />
<Route path="order-summary" element={OrderSummary} />
</Routes>
);
}

export default App;

Next, in app.js I'm going to add a new route path is going to be order-summary and the element
is going to be equal to the OrderSummary component,  make sure to import the component at the
top.

If we now head to the browser and navigate to localhost:3000/order-summary,  we should see the text that our order is confirmed.

Now a page like order confirmation isn't something you navigate to onClick of a button or a link,
It typically happens after an event is successful.

For example, placing an order, so let's add a button on the home page that says place order

so in home.js wrap the JSX with fragments and add the button place order.
what we want to do is onClick of this button, navigate to the order summary page.
To navigate programmatically, React router provides the use navigate hook
let's import it at the top,  import use navigate from React router dom and we can now invoke this hook within the component,
use navigate hook returns a function which we are going to call as navigate
so const navigate is equal to useNavigate() with parentheses
using this navigate function we can now navigate to the order-summary route on click of the button.

so the Home page code looks like below,
import React from 'react'
import { useNavigate } from 'react-router-dom'

export const Home = () => {
const navigate = useNavigate()
return (
<>
<div>Home Page</div>
<button onClick={() => navigate('order-summary')}>Place Order</button>

</>
)
}

Let's save the file and test it out, we're on the home page click on the place order button and we are navigated to the order summary page,  the route is order-summary and we see the text order confirmed.
We have successfully navigated programmatically.

Now implementing a back button programmatically is also done with the useNavigate() hook,
let me show you how,  in order summary component, I'm going to add a back button, so wrap with fragment and then a button that says go back.
Now, let's repeat the same steps as before import useNavigate() hook from react-router-dom, call the hook and assign it to a constant called navigate, which is a function and on click of the button call navigate, but this time we simply want to go back in the browser and for that, we pass in a value of -1. 
So head back to the browser and click on go back, we are navigated back to the home page.

to replace the history of the browser you can use an optional second argument, below is the code for your reference

import React from 'react'
import { useNavigate } from 'react-router-dom'

export const Home = () => {
const navigate = useNavigate()
return (
<>
<div>Home Page</div>
<button onClick={() => navigate('order-summary', { replace: true })}>Place Order</button>

</>
)
}


So, to summarize React router provides the useNavigate() hook to navigate programmatically,  call the hook within the component and use the returned function to navigate passing in either a path
or a number that indicates a change in the history stack.
If you want to replace the history pass in the optional second argument with replace set to true




How to configure a no matching route in our react application

Currently, if we try to navigate to a route that is not configured, for example, localhost:3000/AboutUs, 
we don't see the UI below the navbar and if we take a look at the console you can see we have a warning no routes matched location slash AboutUs.
Now, this scenario is not favorable from a user point of view, a user might assume that the app is still loading or there is an error in the slash AboutUs route.

It would be better is if we inform the user that the URL does not match any route in our application. Let's see how to get that done,

Let's create a new component that should be rendered for URLs that don't match any of the configured routes
so in the components folder let's create a new file called PageNotFound.js,  within the file, I'm going to create a simple component that renders the text page not found.


PageNotFound.js
import React from 'react'

export const PageNotFound = () => {
return (
<div>
Page not found
</div>
)
}


Once we have created the component, we can add a new route in app.js



    <Route path="*" element={<PageNotFound />} />


Route path is going to be equal to asterisk or star and this has a special meaning in React router,  this route will match only when no other routes do, for the element prop we're going to specify the PageNotFound component,  make sure to import it at the top.

App.js

import { Component } from 'react'
import { Routes, Route } from 'react-router-dom'
import { OrderSummary } from './components/OrderSummary';
import { PageNotFound } from './components/PageNotFound';

import Welcome from './components/Welcome'

function App() {
return (
<Routes>
<Route path="/" element={Welcome} />
<Route path="contact" element={Component} />
<Route path="order-summary" element={OrderSummary} />
<Route path="*" element={<PageNotFound />} />
</Routes>
);
}

export default App;


In the browser, if we now navigate to slash AboutUs, we see the page not found text corresponding to the no-match component.

Thank you for reading this article.  I'll see you guys in the next one.


Below is the youtube video for your reference