Home 9 Software Development 9 Creating a Single-Page Application with React Router

Creating a Single-Page Application with React Router

Building a single-page app in a couple of hour is simple with React and Router. Let me walk you through it.
Daniel Zacharias

Eugenio de Tomaso

December 6, 2023
Creating a Single-Page Application with React Router

If you are a software developer and wish to build an app in a couple of hours, React has got you covered! This JavaScript library can help you create an SPA relatively easily. That way, you’ll be joining a very popular bunch — Instagram, Twitter, Gmail, and Facebook, all of which use React Router to create single-page applications.

In this article, we’re going to explain what makes React Router so special and how you can use it to create a single-page app.

React Router: what is it and how it works 

React Router is one of the best React features. Thanks to this particular library, you can enable users to navigate from one page to another or view several pages without needing to reload the browser as an SPA. 

For example, if you type a specific URL into the browser, this will redirect you to a particular route, provided that the UPR path matches a route inside the router file. This is what React Router makes possible, all without the browser reloading.

Also, presenting multiple views in React without React Router is nearly impossible.

What are the benefits of creating a single-page app? The main pro is their user-friendliness. They’re easy to navigate because you don’t redirect the user every single time they change their data. With traditional web apps, this would redirect the user to a new page, which can be a bit annoying when they wish to edit data in several places.

SPAs are static pages that allow the user to go over each step consistently.

Steps in creating SPAs with React Router

Now that we’ve touched briefly on why single-page apps are so desirable, and we defined React Router, let’s guide you through all the steps of creating an SPA, one by one.

Install the React Router

First, you need to create the application template by typing the following command into your project directory:

npm i react-router-dom

The other way of doing this is with a Yarn package manager, which helps you install library packages while offline. Just use this command:

yarn add react-router-dom@6

React Router setup

Now, it’s time for React Router configuration, i.e., to make it available in the app. Use the following commands to import BrowserRouter into the index.js file. 

import React from ‘react’;

import ReactDOM from ‘react-dom/client’; 

import App from ‘./App’;

import { BrowserRouter } from ‘react-router-dom’;

const root = ReactDOM.createRoot( document.getElementById(‘root’) );

root.render(

  <BrowserRouter>

    <App />

  </BrowserRouter>

);

Next, you need to wrap the app component in the Router element. Wrapping is necessary to give the app full access to Routers’s features.

Create SPA components

It’s time to define App’s components, routing, and rendering. 

The app component is the main component. As such, the App component renders all the code you wrote in other components.

The Routes element acts as the parent element, wrapping the individual routes from the app component and making one single route. It’s got two essential attributes: the element attribute and the path attribute. The former defines the rendering component, and the latter defines the URL path.

In the example below, you’ll see that we used a backslash (/) as its path. This is the route that’s first in line for rendering by React. Thus, the home component renders when you start the application. 

By the way, feel free to name the path attribute however you prefer. This system isn’t the same as conditional rendering in React Components.

Here’s what the whole process of defining your Routes should look like:

import { Routes, Route } from ‘react-router-dom’;

import Home from ‘./Home’;

import About from ‘./About’;

import Blog from ‘./Blog’;

function App() {

    return (

      <Routes>

        <Route path=’/’ element={ <Home /> } />

        <Route path=’/about’ element={ <About /> } />

        <Route path=’/blog’ element={ <Blog /> }/>

      </Routes>

    )

}

export default App;

The above code imports and makes Home, About, and Blog components and takes Route and its elements from react-router-dom.

Building the link component

The link component is very similar to <a>, the HTML anchor tag. The only difference is that it uses “to” instead of “href” as its attribute. 

We use the React Router link component to gain access to the different routes we’ve created. 

To create the link component, use the following code:

import { Link } from ‘react-router-dom’;

function Home() {

    return (

      <div>

        <Link to=’/about’>About page</Link>

        <Link to=’/blog’>Blog page</Link>

        <h1>This is the Home Page<h1/>

      </div>

    )

}

export default Home;

Implementing nested routing

The next step in creating an SPA via React’s Router is taking care of nested routing so we can wrap multiple Routes into one. Nested routing is very common when we have some similarity in Routes’ URL paths.

To do this, we have to develop individual Routes for each component:

 import { Routes, Route } from ‘react-router-dom’; 

import Articles from ‘./Articles’;

import NewArticle from ‘./NewArticle’;

import ArticleOne from ‘./ArticleOne’;

function App() {

    return (

      <Routes>

        <Route path=’/article’ element={ <Articles /> }/>

        <Route path=’/article/new’ element={ <NewArticle /> }/>

        <Route path=’/article/1′ element={ <ArticleOne /> }/>

      </Routes>

    )

}

export default App;

The above commands, for example, show the rooting of Article, NewArticle, and ArticleOne components. The similarities in the URL paths are pretty obvious. The only difference between the codes for the path names is the slash (/1) at the end if we look at Articles Route and ArticleOne Route.

It would be much easier to have all three routes nested instead of that, so think about typing these to wrap them up:

import { Routes, Route } from ‘react-router-dom’;

import Articles from ‘./Articles’;

import NewArticle from ‘./NewArticle’;

import ArticleOne from ‘./ArticleOne’;

function App() {

    return (

      <Routes>

        <Route path=’/article’>

          <Route index element={ <Articles /> }/>

          <Route path=’/article/new’ element={ <NewArticle /> }/>

          <Route path=’/article/1′ element={ <ArticleOne /> }/>

        </Route>

      </Routes>

    )

}

export default App;

So, what have we achieved with this? We’ve got three individual routes wrapped in one single Route element. As you can see, the index attribute in the first child Route element indicates this Route’s rendering when you want to navigate to the URL path of the Route parent.

However, you may wish to define your Routes in a component and import it into the app component. This ensures a better quality of your code and makes it more maintainable:

import { Routes, Route } from ‘react-router-dom’;

import Articles from ‘./Articles’;

import NewArticle from ‘./NewArticle’;

import ArticleOne from ‘./ArticleOne’;

function ArticleRoutes() {

    return (

      <Routes>

        <Route index element={ <Articles /> }/>

        <Route path=’/article/new’ element={ <NewArticle /> }/>

        <Route path=’/article/1′ element={ <ArticleOne /> }/>

      </Routes>

    )

}

export default ArticleRoutes;

The final step looks like this:

import { Routes, Route } from ‘react-router-dom’;

import ArticleRoutes from ‘./ArticleRoutes’;

function App() {

    return (

      <Routes>

        <Route path=’/article/*’ element={ <ArticleRoutes /> }>

      </Routes>

    )

}

export default App;

At last, you import the component you created into the app’s component and route it with one Route element. 

After creating the component, you should import it into the app component and route it using a single Route element. The magic trick used here is the added backslash and asterisk symbols. Placing them at the end of the Route’s pathname guarantees the pathname corresponds to any pathname starting with (/article).

Final words

The above instructions should have you all set up to create a single-page app in a relatively short time, perhaps even preventing you from experiencing developer burnout. Without a doubt, React Router can help you do an amazing job, reminding us that React’s library is definitely worth exploring.

Get the best of Code Power News in your inbox every week

    You may also like

    Principles and Benefits of Reactive Programming

    Principles and Benefits of Reactive Programming

    Unlike traditional programming, reactive programming revolves around asynchronous data streams. However, code is usually written linearly, one step after another. Reactive programming offers a way for developers to deal with scenarios where events occur unpredictably...

    Get the best of Code Power News in your inbox every week