How to create a single-page application using React?

Single-page applications are websites that have pages that load inline within the same page. Read on to find how you can create a single page application using React.

What is a single page application?

A single page application (SPA) is essentially a webpage that interacts with the web browser dynamically by rewriting the current web page with the data obtained from the webserver. Hence, in a single page application, the webpage does not reload the page during its runtime and instead works within a browser. 

Single page application vs. multi-page application

Single-page Application

Reloading: Single-page applications work inside a browser and do not require page reloading during webpage executing. 

UI/UX: Offers outstanding user experience by imitating a natural environment with the browser by eliminating wait time and page reloads. It consists of a single web page that loads all content using JavaScript. It requests the markup and data independently and renders pages straight to the browser.  

Examples: Gmail, Google Maps, Facebook, GitHub.

Multi-page Application

Reloading: Multi-page applications work in the traditional way where every change, like displaying the data or submitting data back to the server, renders new pages from the server.

UI/UX: Multi-page applications are larger applications with huge chunks of content, so the user experience is limited compared to single-page applications.  

Examples: eBay and Amazon 

Why choose a single-page application?

The benefits of choosing single-page applications (SPA) are:

  • SPA is quicker since all the webpage resources are loaded only once throughout the application, and data is the only resource that is transmitted.
  • SPA caches local storage effectively as it sends one request, stores all the data, and uses it even when offline.
  • SPA simplifies and streamlines development activities as it eliminates the need to write code to render pages on the server.
  • SPA can be debugged with ease with Chrome as it is possible to investigate page elements and monitor network operations.

When not to use single-page applications?

While SPA does have its advantages, there are certain cases when it is not suitable to use it:

  • SEO: It is difficult and tricky to optimize SPA for SEO since its content is loaded by AJAX (Asynchronous JavaScript and XML). Hence SPAs are not suitable for cases where SEO is critical for business success. 
  • Javascript: It requires users to enable Javascript for proper application and action loading. So it is not suitable for instances where JavaScript might be disabled on the user side. 
  • Security: SPA is also less secure in comparison to MPA, making it unsuitable for highly sensitive applications. SPA has a cross-site scripting (XSS) and allows attackers to inject client-side scripts into the web application.
  • Slow: While the user experience of SPAs on runtime is fast, it is slower to download and can also be slowed down if there are memory leaks in JavaScript. It is hence not suitable for very large applications with a lot of data.

Looking for some fully coded templates? Check out these React examples!

How to build a single-page app using React?

To build a single page app using React, follow the steps mentioned below:

1. Create a react app in your desired location using the following command:

npx create-react-app app-name

A directory called app-name is created with the following default files:

app-name

├── README.md

├── node_modules

├── package.json

├── .gitignore

├── public

│   ├── favicon.ico

│   ├── index.html

│   ├── logo192.png

│   ├── logo512.png

│   ├── manifest.json

│   └── robots.txt

└── src

    ├── App.css

    ├── App.js

    ├── App.test.js

    ├── index.css

    ├── index.js

    ├── logo.svg

    └── serviceWorker.js

 

2. Install react-router-dom for routing requests by executing the following command:

npm install react-router-dom 

3. Wrap the App component.

There are two types of React routers, BrowserRouter (makes URLs like example.com/about) and HashRouter (makes URLs like example.com/#/about). We re using BrowserRouter in this example and use it to wrap the App component.

Your src/index.js file should include the following code:

import React from ‘react’

import { render } from ‘react-dom’

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

import App from ‘./App’

render(

  <BrowserRouter>

    <App />

  </BrowserRouter>,

  document.querySelector(‘#root’)

)

 

4. Create a file named src/pages/HomePage.js with the following code:

import React from “react”;

export default function HomePage() {

return (

<>

<h1>Hey from HomePage</h1>

<p>This is your awesome HomePage subtitle</p>

</>

);

}

5. Create a file named src/pages/UserPage.js with the following code:

import React from “react”;

import { useParams } from “react-router-dom”;

export default function UserPage() {

let { id } = useParams();

return (

<>

<h1>Hello there user {id}</h1>

<p>This is your awesome User Profile page</p>

</>

);

}

 

6. Decide and incorporate the routers that you want to use using Switch and Route. Switch groups all routes together and ensures that they take the precedence from top-to-bottom. Route, on the other hand, defines individual routes.

Your App.js file should include the decided routes.

import React from ‘react’

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

// We will create these two pages in a moment

import HomePage from ‘./pages/HomePage’

import UserPage from ‘./pages/UserPage’

export default function App() {

  return (

    <Switch>

      <Route exact path=”/” component={HomePage} />

      <Route path=”/:id” component={UserPage} />

    </Switch>

  )

}

 

The above code matches the root route (/) to HomePage and matches other pages dynamically to UserPage

 

7. Link to a page within the SPA using Link. 

In the src/pages/HomePage.js file, include the following code:

import React from ‘react’

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

export default function HomePage() {

  return (

    <div className=”container”>

      <h1>Home </h1>

      <p>

        <Link to=”/your desired link”>Your desired link.</Link>

      </p>

    </div>

  )

}

 

You can now run the code and view the development server available at https://localhost:3000

Final Thoughts

That’s all for now, folks! I hope this article will help you kickstart your project using React. If you are excited about it, then you should know that Creative Tim offers free and premium easy to use React Templates. Download the React Themes and Templates developed by Creative Tim today, to create your single page application using React with ease.  

Other useful resources: