How to create a single-page app using React?

How to create a single-page app using React?

Single-page apps 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 app?

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 app vs. multi-page app

Single-page App

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 App

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 app?

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 app?

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.

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 RouteSwitch 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 http://localhost:3000

Conclusion

That’s all for now, folks! We hope this article will help you start your project using React.

If you have any questions or suggestions, please feel free to write in the comments section below! And don’t forget to like and share this article on social media. Enjoy!

Fancy you stumbling on my piece of the internet. Bonjour!

My name is Anmol and I'm the Blogger-In-Chief of this joint & working as the Chief Technology Officer at Azoora, Inc. I'm putting up my views here trying to help creative solopreneurs, developers & designers build their business using the power of websites, apps & social media, this, is, my jam.

If you're looking to start your own online business with a professional high quality website or mobile app, just get in touch. I'd be more than happy to assist.

SKYPE | FACEBOOK | LINKEDIN | TWITTER | EMAIL

Leave a Comment

Your email address will not be published.