Featured

How to Set Up Single-Page Web Applications with React

A React application usually consists of a large number of small files that have interdependencies that you can resolve via the JavaScript module system.

 

You can also use other tools, such as TypeScript or CSS preprocessors. The build process of an application thus quickly becomes costly and complex. For this reason, the Create React App project is a command line tool that makes the initial setup of your application easier and combines all the necessary libraries in such a way that you can start working on your application right away. Create React App, like React itself, is developed by Facebook, and the source code is maintained on GitHub. Create React App is available as an npm package and can either be installed and used as a global package on the system, although this approach is no longer recommended. Alternatively, you can use a feature of your package manager that allows you to use such a package temporarily. Depending on whether you use npm or Yarn as your package manager, you can use one of the following command:

  • npm create react-app <app-name>
  • npx create-react-app <app-name>
  • yarn create react-app <app-name>

Thus, you can use the npm create react-app contact command to create a new React project named contact. In this project, we include the representational state transfer (REST) interface to implement a simple graphical interface for managing contacts.

 

Create React App accepts a few options to control the process of creating a new app. The most important ones include the following:

  • --use-npm: By default, Create React App uses Yarn as the package manager. If you do not want this, you can force the use of npm with this option.
  • --template <template>: Create React App supports the use of templates. These are templates for building and configuring a React application. A very popular example of such a template is the TypeScript template. It prepares your application for the use of TypeScript so that you develop React using TypeScript rather than JavaScript.

For more information on how to use Create React App, see the project’s documentation at https://create-react-app.dev/docs/getting-started.

 

The structure generated by Create React App is divided into three parts: the root directory, the public directory, and the src directory. These sections serve different purposes during development, so let’s consider this structure briefly next:

  • In the root directory, you’ll find the most important configuration files for your project, including the json and package-lock.json files required by npm to manage the project. You can also find the .gitignore file in this directory, which already has a set of default entries regarding files and directories that should not be included in version control. The README.md file contains the documentation of the project. In this file, you can record everything that’s important for developers participating in the project.
  • The public directory contains the static content delivered by a web server, including, for example, media files, but also the html file, the central entry file into the application.
  • You’ll spend most of your time in the src directory during development. In this directory, you’ll store the source code of your components and any other JavaScript files. Create React App creates an js file in this directory, which is the entry point to the app, and creates an initial component with the filename App.js.

Your application is already executable in the initial state generated by Create React App, so you can start it from the command line in the root directory of the application using the npm start command. Once you have confirmed the command, the application is launched in watch mode, your system’s default browser opens, and the application is displayed. Watch mode means that a script watches your application’s files and automatically updates the browser with the latest version of the source code whenever you save changes to a file. By default, the application is accessible at http://localhost:3000/. If this port is already being used, the application will be redirected to another free port.

 

The index.html file in the public directory is a simple HTML file. This file has only one peculiarity: There’s a <div> element that has the root value for the id attribute. React inserts the application into this container. For a user, first a white page is displayed for a short time and then will the application become visible. As a rule, this white page is only visible for such a short time that a user doesn’t notice. However, if your application takes longer to render, for example, because it is very complex, you can solve this problem using server-side rendering.

 

Server-side Rendering: The idea behind server-side rendering is that the single-page application is not first built in the user’s browser but is already prepared on the server side. For this purpose, React runs in a Node.js environment and does the same work as it does in the browser, the difference being that the HTML structure is not displayed directly; instead, a JavaScript string is sent to the browser. The result is that the user already receives a prepared React application. React then just takes control of the previously static HTML structure and makes it respond dynamically to the user’s interactions. This process is referred to as hydration. Once the process is complete, the application behaves like a regular React application.

 

The build process of React modifies the index.html file so that the application’s processed and optimized JavaScript files are loaded. The first file loaded is index.js. Listing 10.1 shows an excerpt from this file.

 

const root = ReactDOM.createRoot(

   document.getElementById('root') as HTMLElement

);

root.render(

   <React.StrictMode>

       <App />

   </React.StrictMode>

);

 

React is divided into two parts—renderer and reconciler. The renderer ensures that the structure of the application is built for the target platform. The reconciler, the heart of React, manages the component tree and, when changes are made, calculates the new version of the application that’s presented to the user. The reconciler is implemented in such a way that it isn’t platform-specific, so it can be used both in the browser and for mobile applications. The renderer, on the other hand, is platform specific. Our example uses the Document Object Model (DOM) renderer, which renders React in the browser. For example, another popular renderer is React Native, which lets you create native mobile apps.

 

As shown in the code above, you pass a component hierarchy written in JSX to the render method of the root object. You create the root object via the createRoot method to which you pass a reference to the DOM node where the application will be included.

 

JSX: JavaScript and XML: JSX is a syntax extension for JavaScript that allows you to write HTML strings directly in JavaScript. There’s a difference between React elements and React components. Elements start with a lowercase letter and are translated directly into HTML tags, for example, <div></div>. Components start with an uppercase letter and must first be imported before they can be used. These components are based on JavaScript functions or classes. An example of the inclusion of a component is <App />.

 

Inside a JSX expression, you can again write JavaScript, but you must enclose it in curly brackets. In this way, JSX and JavaScript can be nested together in any way. JSX are ordinary JavaScript expressions that you can assign to variables or use as return values of functions.

 

You don’t necessarily have to use JSX in a React application. Instead of writing elements and components as tags, you can also use the createElement function. The disadvantage of this variant is that the source code quickly becomes confusing, and nesting in particular can only be mapped awkwardly.

 

The StrictMode component used in the index.js file is similar to the strict mode in Java- Script. This component turns on additional checks and warnings for React applications to highlight potential sources of errors. For example, you’ll be warned if you trigger unexpected side effects or use unsafe lifecycle methods. To learn more about Strict- Mode, you should visit https://reactjs.org/docs/strict-mode.html.

 

The index.js file includes the app component by default, which a root component prepared by Create React App. The app component is the entry point to the component tree and thus to our next topic: components in React.

 

Editor’s note: This post has been adapted from a section of the book Full Stack Web Development: The Comprehensive Guide by Philip Ackermann.

Recommendation

Full Stack Web Development
Full Stack Web Development

Full stack web developers are always in demand—do you have the skillset? Between these pages you’ll learn to design websites with CSS, structure them with HTML, and add interactivity with JavaScript. You’ll master the different web protocols, formats, and architectures and see how and when to use APIs, PHP, web services, and other tools and languages. With information on testing, deploying, securing, and optimizing web applications, you’ll get the full frontend and backend instructions you need!

Learn More
Rheinwerk Computing
by Rheinwerk Computing

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

Comments