DEV Community

Cover image for How to Build a Single Page Application (SPA) with React
Seyed Ahmad
Seyed Ahmad

Posted on

How to Build a Single Page Application (SPA) with React

In today’s web development world, Single Page Applications (SPAs) are widely used because of their ability to provide a smooth user experience by dynamically loading content without requiring full page reloads. With React, a powerful JavaScript library for building user interfaces, creating an SPA becomes even easier and more efficient. This article will guide you through the process of building an SPA with React, covering the core concepts and essential steps needed for a successful project.

What is a Single Page Application (SPA)?

Build a Single Page Application (SPA) with React
A Single Page Application is a web application that interacts with the user by dynamically rewriting the content of the page rather than loading entire new pages from a server. This results in faster navigation and a smoother user experience since most resources like HTML, CSS, and JavaScript are only loaded once.

In SPAs, the navigation is handled on the client-side using JavaScript, and React is one of the most popular tools to build such applications. Let's explore how React makes this possible.

Setting Up Your React Project

Before we dive into coding, we need to set up the React environment. You can quickly scaffold a new React project using Vite or Create React App (CRA). For simplicity, let’s use CRA in this example.

1-Install Node.js: Make sure you have Node.js installed on your system. You can verify this by running the following commands in your terminal:

node -v
npm -v
Enter fullscreen mode Exit fullscreen mode

2-Create a New React Project: Now, use the following command to create a new React project:

npx create-react-app my-spa-app
Enter fullscreen mode Exit fullscreen mode

Once the project is set up, navigate into the project directory:

cd my-spa-app
Enter fullscreen mode Exit fullscreen mode

3-Start the Development Server: You can run the development server by using:

npm start
Enter fullscreen mode Exit fullscreen mode

This will start the application, and you’ll see the default CRA homepage in your browser at http://localhost:3000/.

Creating the Structure of Your SPA

Now that you have the basic setup, let’s break down how you can structure an SPA with multiple views (pages) and a navigation system using React Router.

1-Install React Router: React Router is a popular library used for adding navigation in React applications. To install it, run:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

2-Setting Up Routing: Open the src folder and modify App.js to set up routing for different views.

First, import the necessary components from React Router:

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

const Home = () => <h2>Home Page</h2>;
const About = () => <h2>About Page</h2>;
const Contact = () => <h2>Contact Page</h2>;

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

In the code above:

  • We use BrowserRouter (renamed as Router) to wrap our application.
  • Link is used to create navigational links, replacing the standard tag in SPAs.
  • The Switch component ensures that only one Route is rendered at a time. 3-Creating Component Views: You can move the content of Home, About, and Contact to separate components for better structure. Create three files inside the srcfolder: Home.js, About.js, and Contact.js.

Here’s how the Home.js file might look:

import React from 'react';

const Home = () => {
  return (
    <div>
      <h2>Welcome to the Home Page</h2>
      <p>This is the main landing page of your SPA.</p>
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

Similarly, create components for About.js and Contact.js.

4-Handling 404 Pages: It’s good practice to handle unknown routes in your SPA. To do this, you can add a fallback Route at the bottom of your Switch block:

<Route path="*">
  <h2>404 - Page Not Found</h2>
</Route>
Enter fullscreen mode Exit fullscreen mode

This will ensure that any unknown routes are handled gracefully with a custom 404 page.

Managing State in Your SPA

React’s state management system lets you keep track of your application’s data, like form inputs or user interactions. For simple state management, you can use React’s built-in useState and useEffect hooks.

Here’s a quick example:

import React, { useState } from 'react';

const Contact = () => {
  const [formData, setFormData] = useState({ name: '', message: '' });

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted:', formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="name"
        value={formData.name}
        onChange={handleChange}
        placeholder="Your Name"
      />
      <textarea
        name="message"
        value={formData.message}
        onChange={handleChange}
        placeholder="Your Message"
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Contact;
Enter fullscreen mode Exit fullscreen mode

In this code:

  • We use useState to handle form inputs.
  • When the user submits the form, the state is logged to the console.

Optimizing Your SPA

Once your SPA is functional, you can enhance its performance and user experience:

1-Code Splitting: React allows you to load parts of your application lazily, which improves performance. For example:

import React, { Suspense, lazy } from 'react';

const About = lazy(() => import('./About'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Route path="/about" component={About} />
    </Suspense>
  );
}
Enter fullscreen mode Exit fullscreen mode

With code splitting, only the necessary JavaScript is loaded when the user navigates to a particular route, making your application faster.

2-SEO Considerations: While SPAs generally have limitations with SEO, you can use Next.js, a React framework for server-side rendering (SSR), to optimize for SEO and improve your app’s visibility.

Conclusion
Building an SPA with React offers immense flexibility and control over your web application. From setting up routes to managing state, React simplifies the process of creating fast, dynamic, and scalable applications. By leveraging modern React practices, such as lazy loading and client-side routing, you can enhance both performance and user experience.

If you’re looking for professional services to build or enhance your single-page applications, I offer custom SPA development using React and Next.js. Whether you need to build from scratch or optimize an existing project, I can help.

Get in touch with me through [SeyedAhmadDev@gmail.com] or WhatsApp at [+989034260454] to discuss your project needs.

Top comments (2)

Collapse
 
reactdeveloper profile image
Barf Biseda

This is helpful 😁

Collapse
 
seyed_ahmadgholami_36bc9 profile image
Seyed ahmad Gholami

This helped me to developed my first app with react, thanks