Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to set up routing in ReactJS. explain with the help of step by step approach?

Introduction

ReactJS is a powerful JavaScript library for building user interfaces, particularly single-page applications where you need a fast, interactive user experience. One feature that makes single-page apps more user-friendly is the ability to navigate between different parts of the application, like you would on a traditional multi-page site. This is where routing comes into play.

In simple terms, routing is like a guide map of a large super mall. When you enter the mall, you might need to go to a specific store. The guide map helps you find it without having to wander around aimlessly. Similarly, routing in ReactJS helps in navigating through different components without reloading the entire page.

In this blog post, we're going to learn how to set up routing in ReactJS using the React Router library and we'll do it step by step. This post is intended for someone who's just starting their journey in programming, so we'll break down everything into simpler terms and provide plenty of code examples.

What is React Router?

React Router is a standard library for routing in React. It keeps your UI in sync with the URL and lets you handle routes in a way that is easy to manage and understand. It uses a component structure to call components, which display the appropriate information.

Imagine you're at a theme park. Each ride or attraction is a different 'component'. The park map (our router) helps you find the correct attraction (component) based on where you want to go.

Installing React Router

Before we start with the actual routing, we need to install the React Router library. Make sure you already have a React application set up. If you don't, you can create a new one by running npx create-react-app my-app. Replace "my-app" with whatever you'd like to name your application.

Now, navigate into your new application's directory using cd my-app, and install React Router by running npm install react-router-dom.

npx create-react-app my-app
cd my-app
npm install react-router-dom

Setting Up Basic Routes

Now that we have React Router installed, let's create some basic routes. In our theme park analogy, we're going to define the paths to a few of our attractions.

Let's start by creating three components: Home.js, About.js, and Contact.js. These will be our different 'attractions'.

Here's how we might define the Home component in Home.js:

import React from 'react';

function Home() {
  return <h2>Home</h2>;
}

export default Home;

You can define About and Contact in the same way, just replace 'Home' with 'About' or 'Contact'.

Now, let's set up our routes. First, import BrowserRouter, Route, and Link from react-router-dom in your App.js file.

import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

BrowserRouter is a component that uses the HTML5 history API to keep your UI in sync with the URL. We're going to wrap our entire app in this component.

Route is the conditionally shown component based on the path. It's like the guide that checks your map and takes you to the component you want to see.

Link is used for linking to different routes. It's like the signpost in the park that points you in the right direction.

Next, let's define our routes within the Router component:

import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>

        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </div>
    </Router>
  );
}

export default App;

Here, we've created a simple navigation bar with Link components that point to different paths. The to prop in each Link matches the path prop in our Route components. When a link is clicked, the Route with the matching path is rendered.

The exact prop on the / route ensures that route is only matched exactly. Without it, the Home component would also render when 'About' or 'Contact' is clicked because all paths start with /.

This is a basic setup for routing in a React application. From here, you can expand to include more routes, nested routes, route parameters, and more.

Conclusion

In this blog post, we learned about React Router and how to set up basic routing in a React application. We covered the installation of React Router, creation of components, and setting up routes using BrowserRouter, Route, and Link.

Remember, routing in React is like a map to a theme park. Each path leads to a different attraction (or component). React Router makes it easy to control what's displayed based on the path, creating a more interactive and user-friendly application. Keep experimenting with different routes and components to get a better understanding of how routing in React works!