6

Creating a Project with React

In this chapter, we’ll focus on understanding frontend development and creating a web frontend project with React. In previous chapters, we mostly focused on Django and Django Rest. In this chapter, we’ll explain the basics of frontend development. Next, we will introduce the React library and create a starting project for the following chapters. Finally, we will learn how to configure our project.

In this chapter, we will cover the following topics:

  • Understanding frontend development
  • Creating the React project
  • Configuring the project
  • Useful ES6 and React features

Technical requirements

In this book, we use the Linux OS, but you can find the tools needed for this project on other OSs as well. We’ll see how to install Node.js and Visual Studio Code (VS Code) on your machine in this chapter.

The following GitHub link will also be required: https://github.com/PacktPublishing/Full-stack-Django-and-React/tree/chap6.

Understanding frontend development

Frontend development is the part of software development that focuses on the User Interface (UI). In web development, frontend development is the practice of producing HTML, CSS, and JavaScript for a website or web application.

HTML stands for HyperText Markup Language. HTML displays content on the page, such as text, buttons, links, headings, or lists.

CSS is defined as Cascade Style Sheets. CSS is used to style the web page. It deals with things such as colors, layouts, and animation. It also helps with the accessibility of your websites so that everyone can easily use your website.

Finally, JavaScript is a client-side language that facilitates user interaction and makes dynamic pages. It can help with complex animations, form validation, data fetching from a server, and data submission to the server.

However, as with languages such as Python, while building a frontend application from scratch with HTML, CSS, and JavaScript is definitely possible, it is quite difficult. It requires good knowledge of code architecture and component reusability. In the end, you’ll end up creating your own development framework.

But why not directly use some pre-built CSS or JavaScript framework?

Tools such as Vue, Angular, or React can help you write frontend applications with seed and in a smoother way.

In this book, we’ll be using React’s open source JavaScript library. Let’s learn more about React as a library.

What is React?

React is a library that helps developers build reactive UIs as a tree of small reusable pieces called components.

In frontend development, a component is a mixture of HTML, CSS, and JavaScript that captures the logic required to render a small section or a larger UI. Let’s analyze the following HTML form to better understand components in frontend development:

Figure 6.1 – HTML form

Figure 6.1 – HTML form

As you can see in Figure 6.1, in the form, we have defined four components:

  • The Name input
  • The Email input
  • The Message input
  • The Submit button

Each of these components has its own logic. For example, the Submit button will validate the form and save or send the message to a remote source.

React is defined as a library instead of a framework because it only deals with UI rendering and leaves many of the other things that are important in development to the developers or other tools.

To build a React application, you’ll need the following stack:

  • Application code: React, Redux, ESLint, Prettier, and React Router
  • Build tools: Webpack, Uglify, npm/yarn/pnpm, and babel
  • Testing tools: Jest and Enzyme

You’ll need to add these dependencies to your React project to optimize and perform some tasks – that’s where React differs from tools such as Angular, which comes with its own stack for routing, for example.

Now that we better understand React, let’s create a React project.

Creating the React project

Before creating the React project, we need to have tools installed for a better development experience. These tools are drivers, editors, and plugins basically. Let’s start by installing Node.js.

Installing Node.js

Node.js is an open source and powerful JavaScript-based server-side environment. It allows developers to run JavaScript programs on the server side, even though JavaScript is natively a client-side language.

Node.js is available for multiple OSs, such as Windows, macOS, and Linux. In this book, we are working on a Linux machine and Node.js should normally be installed already by default.

For other OSs, you can find the installation package at https://nodejs.org/en/download/. Download the latest Long-Term Support (LTS) version for your OS.

When visiting the link, you’ll have an output similar to the following screenshot:

Figure 6.2 – Node.js installers

Figure 6.2 – Node.js installers

To check whether Node.js has been installed on your Linux machine, open the Terminal and enter the following commands:

node -v
yarn -v

These commands should show you the versions of Node.js and yarn installed:

Figure 6.3 – node and yarn versions

Figure 6.3 – node and yarn versions

If you don’t have yarn installed on your machine, you can install it with the npm package:

npm install -g yarn

yarn and npm are package managers for JavaScript. We’ll use the yarn package manager a lot in upcoming chapters to install packages, run tests, or build a production-ready version of the frontend. However, feel free to use npm if you want. Just don’t forget that the commands are slightly different.

The basic tools to develop with JavaScript have now been installed. Next, we will need to install VS Code and configure it to make JavaScript development easier.

Installing VS Code

VS Code is an open source code editor developed and maintained by Microsoft. It supports multiple programming languages and with the plugins and extensions, you can easily transform it into a powerful IDE. However, you can also use other editors such as Atom, Brackets, or the powerful IDE WebStorm. Feel free to use what you are familiar with.

VS Code is available for Windows, macOS, and Linux and you can download the right version for your OS at https://code.visualstudio.com/.

Once it’s installed and opened, you’ll see the following window:

Figure 6.4 – VS Code window

Figure 6.4 – VS Code window

VS Code comes with an integrated terminal that you can use to create and run React apps. Note also that you can open projects with VS Code using the following command in the terminal in the directory of the project:

code .

You can find the integrated terminal in the View | Integrated Terminal menu.

With the basics of VS Code explored, let’s add the needed extensions to make React development more enjoyable.

Adding VS Code extensions

Every programming language and framework comes with a lot of extensions available to make development easier and more enjoyable. These extensions include code snippets, testing, project environment configuration, and code formatting. In VS Code, if you open Extensions in the activity bar (the bar on the left), you can find a search bar to look for different extensions.

For the React project, let’s start by adding the ES7+ React/Redux/React-Native/JS snippets extension. This extension will suggest code snippets when writing code in React files. It should look something like this:

Figure 6.5 – ES7 + React/Redux/React-Native/JS snippets extension

Figure 6.5 – ES7 + React/Redux/React-Native/JS snippets extension

After that, let’s install the ESLint extension. It’ll help you find typos and syntax errors quickly by automatically formatting the code and showing formatting errors. This makes the ES code formatting rules easy to understand. The ESLint extension looks like this:

Figure 6.6 – The ESLint extension

Figure 6.6 – The ESLint extension

Next, we will add another VS Code extension called Prettier. Prettier is a code formatter that not only makes your code visually appealing but also much more structured for readability. You can find a VS Code extension that can help you format your code automatically after saving your code. The extension looks something like this:

Figure 6.7 – Prettier code formatter

Figure 6.7 – Prettier code formatter

And finally, but optionally, we have indent-rainbow. If you have many blocks of code with parents and children, it can become quite difficult to read. This extension will make JavaScript code with indentation more readable. It looks like this:

Figure 6.8 – The indent-rainbow extension

Figure 6.8 – The indent-rainbow extension

Great! With these extensions installed in VS Code, we can now move on to creating the React application.

Creating and running a React app

With Node.js and VS Code installed and configured, we have everything we need to create our first React.js application.

To create our React app, we’ll be using create-react-app (https://github.com/facebook/create-react-app), a simple command for creating a modern web React application. Follow these steps to create your first React application and modify the code:

  1. Run the following command to create a React application:
    yarn create react-app social-media-app

This command will create a React application named social-media-app. If you are using npm, then replace yarn with npx. After installation, you will have an output similar to the following screenshot:

Figure 6.9 – The React project creation terminal output

Figure 6.9 – The React project creation terminal output

Inside social-media-app, you’ll find a file called package.json. This file contains all the configurations for the JavaScript project, starting from basic information about the project, such as the name, the version, and the developers, but it also includes a list of installed packages and the scripts related to starting the server, for example.

  1. Run the created React application with the following command:
    yarn start
  2. Open your browser and specify localhost:3000 as your web link. Once done, it will look something like this:
Figure 6.10 – Running the React application

Figure 6.10 – Running the React application

The application is running. Now, let’s modify the code in the React application.

  1. Open the App.js file from the src folder in the VS Code editor.
  2. Modify the text inside the App.js file from Learn React to Hello World and save the file:
Figure 6.11 – The App.js code

Figure 6.11 – The App.js code

  1. Check the browser again and you’ll see the changes:
Figure 6.12 – Modified React application

Figure 6.12 – Modified React application

React has a hot reload feature, meaning that any changes made to a file in the project are reflected in the rendering of the web application.

Great! We’ve just installed a React application and modified the code.

Let’s install some tools in the browser for debugging the React application.

Installing a debugging plugin in the browser

To debug React applications, we have to install React Developer Tools, a plugin available on Chrome, Firefox, and Edge browsers. You can find the plugin for the Chrome version at https://chrome.google.com/webstore/category/extensions and the Firefox version at https://addons.mozilla.org. The plugin looks something like this:

Figure 6.13 – The React browser plugin

Figure 6.13 – The React browser plugin

Once it’s installed, you can open the developer tools by pressing Ctrl + Shift + I (or F12) in the Chrome browser. The following screenshot shows the developer tools in the Firefox browser:

Figure 6.14 – React application with the open React extension

Figure 6.14 – React application with the open React extension

This tool will be useful for finding bugs and debugging the application in the development phase.

The project is created and can now be successfully run. Let’s install and configure some packages for routing and styling in the next section.

Configuring the project

Before starting to write the authentication flow, let’s make sure that the project is ready for coding. In this section, we will configure styling and routing, and allow the request on the API.

Let’s start with routing first.

Adding React Router

Routing in a frontend application represents everything that deals with moving from one view to another and loading the right page using the right URL.

React doesn’t come with an integrated routing package, so we’ll use the react-router package.

You can install the package using the following command:

yarn add react-router-dom@6

Then, edit the index.js file like so:

src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import "./index.css";
import App from "./App";
// Creating the root application component
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
 <React.StrictMode>
   <BrowserRouter>
     <App />
   </BrowserRouter>
 </React.StrictMode>
);

In the preceding code block, we imported the BrowserRouter component and wrapped it inside the React.StrictMode component which helps us receive warnings in the development mode (https://reactjs.org/docs/strict-mode.html), and finally, the App component is wrapped inside the BrowserRouter component.

With React Router configured, we can freely move on to installing React Bootstrap for styling.

Adding React Bootstrap

React is easily configurable with CSS frameworks. For this project, for the sake of simplicity and rapidity of development, we’ll go with Bootstrap.

Fortunately, the React ecosystem provides a package called react-bootstrap independent of JQuery.

Run the following command to install the package:

yarn add react-bootstrap bootstrap

Next, import the bootstrap CSS file into the index.js file like so:

src/index.js

...
import 'bootstrap/dist/css/bootstrap.min.css';
import App from "./App";
...

With react-router and react-bootstrap installed, let’s create a quick page using both of these in the next subsection.

Creating the Home page

Creating a page in React using React Router follows this pattern most of the time:

  • Creating the component and the page
  • Registering the page in BrowserRouter with an URL

Follow these steps to create the Home page:

  1. Create a directory in src called pages.
  2. Inside the pages directory, create a new file called Home.jsx:
Figure 6.15 – The pages folder structure

Figure 6.15 – The pages folder structure

This file will contain the UI for the Profile page.

  1. Add the following text to the Home.jsx file to ensure that authentication is working properly:

src/pages/Home.jsx

import React from "react";
function Home() {
 return (
   <div>
     <h1>Profile</h1>
     <p>
       Welcome!
     </p>
   </div>
 );
}
export default Home;
  1. Register this page in the App.js file:

src/App.js

import React from "react";
import { Route, Routes } from "react-router-dom";
import Home from "./pages/Home";
function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
    </Routes>
  );
}
export default App;

To register a page with React Router, you use the <Route /> component and pass two props:

  • The path
  • The component element
  1. With the preceding code added, make sure that the React project is running. You can check the page at http://127.0.0.1:3000:
Figure 6.16 – Home page

Figure 6.16 – Home page

Great! With this added, let’s quickly configure the Django project to avoid some request issues in the next section.

Configuring CORS

CORS stands for cross-origin resource sharing. It’s a browser mechanism that enables controlled access to resources located outside of a given domain.

It helps prevent cross-domain attacks or unwanted requests. In the case of this project, the React project is running on http://127.0.0.1:3000.

If we try to make some requests from the browser, we’ll receive an error. Open the React application at http://127.0.0.1:3000 and open Developer Tools:

Figure 6.17 – Opening the developer tools

Figure 6.17 – Opening the developer tools

Also, make sure that the Django server is running.

In the console, enter the following line:

fetch("http://127.0.0.1:8000/api/post/")

You’ll receive an error:

Figure 6.18 – A CORS error when making a request

Figure 6.18 – A CORS error when making a request

Let’s quickly configure the Django API side by following these steps:

  1. Enable CORS with Django REST by using django-cors-headers:
    pip install django-cors-headers
  2. If the installation of the django-cors-headers package is complete, go to your settings.py file and add the package into INSTALLED_APPS and the middleware:

CoreRoot/settings.py

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]
  1. Add these lines at the end of the settings.py file:

CoreRoot/settings.py

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000"
]
  1. Make the request again in Developer Tools.

You will see that the request has passed, and we are good now. The API is ready to accept requests from the React application:

Figure 6.19 – Trying a successful request in Developer Tools

Figure 6.19 – Trying a successful request in Developer Tools

With the React project configured with the backend for a better development experience, we can now explore the ES6 (ECMAScript 6) and React features that we will use a lot in upcoming chapters.

Useful ES6 and React features

JavaScript and React are evolving languages and technologies, incorporating exciting, new features each year. ES6, also known as ECMAScript 2015, is a significant enhancement in the JavaScript language that allows developers to write programs for complex applications with better techniques and patterns.

With React, we have moved from writing classes to writing components using functions and React Hooks. In this section, we will quickly explore the ES6 syntaxes, React concepts, and React Hooks that we will use in the following chapters.

const and let

The const keyword was introduced in ES6 and it makes any variables immutable when declared with the keyword. When using the const keyword, variables can’t be redeclared nor reassigned. Here’s an example of its usage:

Figure 6.20 – Usage of the const keyword

Figure 6.20 – Usage of the const keyword

On the other hand, let is used to declare a variable that can be reassigned to a new value. This is useful when you want to create a variable that can change over time, such as a counter or an iterator. Here’s an example:

let counter = 0;
// This is allowed because counter is not a constant
counter++;

In general, it is a good practice to use const by default, and only use let when you need to reassign a variable. This can help to make your code more readable and prevent accidental reassignments.

Now that we understand the usage of const and let keywords, let’s move on to understanding template literals in JavaScript.

Template literals

In JavaScript, template literals are a way to define string values that can contain placeholders for dynamic values. They are represented by the backtick (`) character and use the dollar sign ($) and curly braces ({}) to insert expressions into the string.

Here is an example of a template literal:

const name = 'World;
const message = `Hello, ${name}!`;
console.log(message); // "Hello, World!"

In this example, we defined a template literal named message that contains a placeholder for the name variable. When the template literal is evaluated, the name variable is inserted into the string and the resulting string is logged to the console.

Template literals provide a more convenient and readable way to create strings with dynamic values compared to using the traditional string concatenation operator (+). They also support string interpolation, which means that you can insert expressions into the string, as well as multiline strings. Here’s an example:

const a = 10;
const b = 20;
const message = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(message); // "The sum of 10 and 20 is 30."

In the preceding example, we defined a template literal called message that contains multiple expressions that are inserted into the string when the template literal is evaluated. This allows us to create a string with dynamic values that is more readable and concise than when using string concatenation.

Now that we understand what template literals are, let’s explain JSX styling in React.

JSX styling

JSX is a syntax extension to JavaScript that allows you to write JavaScript code that looks like HTML. It was introduced by Facebook as part of the React library, but it can be used with other JavaScript libraries and frameworks as well. Here is an example of how you might use JSX in a React component:

import React from 'react';
function Component() {
  return (
    <div>
      <h1>Hello, world!</h1>
      <p>This is some text.</p>
    </div>
  );
}

In the preceding example, we defined a React component called Component that returns some JSX code. The JSX code looks like HTML, but it is transformed into JavaScript by the React library, which generates the appropriate elements and attributes in the DOM.

When you write JSX, you can use JavaScript expressions inside the curly braces ({}) to insert dynamic values into the JSX code. This allows you to easily create dynamic and interactive UIs using JSX:

import React from 'react';
function Component({ name }) {
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>This is some text.</p>
    </div>
  );
}

In the preceding example, we defined a React component called Component that takes a name prop and inserts it into the JSX code using a JavaScript expression. This allows us to create a dynamic and personalized greeting for the user.

Now that we understand how JSX works with React, let’s explain the concept of props and states.

Props versus states

In React, props and states are two different ways to manage data in a component.

Props are short for properties and are used to pass data from a parent component to a child component. Props are read-only, which means that a child component cannot modify the props passed to it by the parent component:

import React from 'react';
function ParentComponent() {
  return (
    <ChildComponent
      name="John Doe"
      age={25}
    />
  );
}
function ChildComponent({ name, age }) {
  return (
    <p>
      My name is {name} and I am {age} years old.
    </p>
  );
}

In the preceding code, we defined a parent component called ParentComponent that renders a child component called ChildComponent and passes two props to the child component (name and age). The child component receives these props as arguments and uses them to render the content of the component. Because props are read-only, the child component cannot modify the name and age props passed to it by the parent.

On the other hand, a state is a way to manage data in a component that can be modified by the component itself. The state is private to the component and can only be modified using special React methods, such as useState.

Here is an example of how you might modify a state in a React component:

import React, { useState } from 'react';
function Counter() {
  // Use useState to manage the state of the counter
  const [count, setCount] = useState(0);
  // Function to increment the counter
  function handleIncrement() {
    setCount(count + 1);
  }
  return (
    <div>
      <p>The counter is at {count}.</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}

In the preceding code, we define a component called Counter that uses the useState Hook to manage the state of a counter. The useState Hook returns an array with two elements, the current value of the state (in this case, count) and a function to update the state (in this case, setCount).

In the render method of the component, we display the value of the count state and define a button that, when clicked, calls the handleIncrement function to update the count state. This causes the component to re-render and display the updated value of the count state.

Now that we understand the difference between props and state better, let’s dive deeper into understanding the useState Hook.

Important note

useState is a Hook in React that allows you to add a state to functional components. In other words, useState allows you to manage the state of your component, which is an object that holds information about your component and can be used to re-render the component when this state changes.

The Context API

The Context API is a way to share data between different components in a React application. It allows you to pass data through the component tree without having to pass props down manually at every level. Here is an example of how you might use the Context API in a React application:

// Create a context for sharing data
const Context = React.createContext();
function App() {
  // Set some initial data in the context
  const data = {
    message: 'Hello, world!'
  };
  return (
    // Provide the data to the components inside the
    // Provider
    <Context.Provider value={data}>
      <Component />
    </Context.Provider>
  );
}
function Component() {
  // Use the useContext Hook to access the data in the
  // context
  const context = React.useContext(Context);
  return (
    <p>{context.message}</p>
  );
}

In the preceding code, we use the React.createContext method to create a new context object, which we call Context. We then provide some initial data to the context by wrapping our top-level component in a Context.Provider component and passing the data as the value prop. Finally, we use the useContext Hook in Component to access the data in the context and display it in the component.

There is also another Hook that we will use in this book. Let’s explain the useMemo Hook in the next section.

useMemo

useMemo is a Hook in React that allows you to optimize the performance of your components by memoizing expensive calculations. It works by returning a memoized value that is only recalculated if one of the inputs to the calculation changes.

Important note

Memoization is a technique used in computer programming to speed up programs by storing the results of expensive function calls and returning the cached result when the same inputs are given again. This can be useful for optimizing programs that make many repeated calculations with the same input.

Here is an example of how you might use useMemo to optimize the performance of a component:

import React, { useMemo } from 'react';
function Component({ data }) {
  // Use useMemo to memoize the expensive calculation
  const processedData = useMemo(() => {
    // Do some expensive calculation with the data
    return expensiveCalculation(data);
  }, [data]);
  return (
    <div>
      {/* Use the processed data in the component */}
      <p>{processedData.message}</p>
    </div>
  );
}

In the preceding code, we use useMemo to memoize the result of an expensive calculation that we do with the data prop passed to the component. Because useMemo only recalculates the value if the data prop changes, we can avoid making the expensive calculation every time the component is re-rendered, which can improve the performance of our application.

In the React project that we will build in the next chapter, we will work with forms using React and the Hooks provided by the React library. Let’s learn more about controlled and uncontrolled components.

Handling forms – controlled components and uncontrolled components

A controlled component is a component in React that is controlled by the state of the parent component. This means that the value of the input field is determined by the value prop passed to the component, and any changes to the input are handled by the parent component.

Here is an example of a controlled component:

import React, { useState } from 'react';
function Form() {
  // Use useState to manage the state of the input field
  const [inputValue, setInputValue] = useState('');
  // Function to handle changes to the input field
  function handleChange(event) {
    setInputValue(event.target.value);
  }
  return (
    <form>
      <label htmlFor="name">Name:</label>
      <input
        type="text"
        id="name"
        value={inputValue}
        onChange={handleChange}
      />
    </form>
  );
}

In the preceding code, we use useState to manage the state of the input field and the handleChange function to update the state when the input is changed. Because the value of the input is determined by the inputValue state variable, the input is considered to be a controlled component.

On the other hand, an uncontrolled component is a component in React that manages its own state internally. This means that the value of the input field is determined by the defaultValue prop passed to the component, and any changes to the input are handled by the component itself.

Here is an example of an uncontrolled component:

import React from 'react';
function Form() {
  // Use a ref to manage the state of the input field
  const inputRef = React.useRef();
  // Function to handle the form submission
  function handleSubmit(event) {
    event.preventDefault();
    // Do something with the input value here
    // For example, you might send the input value to an
    // API or save it to the database
    sendInputValue(inputRef.current.value);
    // Clear the input after submitting
    inputRef.current.value = '';
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input
        type="text"
        id="name"
        defaultValue=""
        ref={inputRef}
      />
    </form>
  );
}

In this example, we used ref to manage the state of the input field and the handleSubmit function to handle the form submission. Because the value of the input is determined by the defaultValue prop and managed internally by the component, the input is considered to be an uncontrolled component.

In this section, we have explored most of the React and ES6 features that we will use in the next chapters. We will mostly be working with React Hooks, JSX, and interesting ES6 features such as template literals and let/const keywords.

Summary

In this chapter, we’ve explained frontend development and created a React application by installing Node.js and VS Code. We then configured it for better development using VS Code. React will also run in the browser, so we installed some plugins that will make debugging easier.

Then, we started coding a little bit with basic configuration for routing, styling, and CORS configuration to allow requests on the Django API. Finally, we explored the React and ES6 features that we will be using in the next chapters.

In the next chapter, we’ll familiarize ourselves more with React by building a login and register page while explaining component-driven development.

Questions

  1. What are Node.js and yarn?
  2. What is frontend development?
  3. How do you install Node.js?
  4. What is VS Code?
  5. How do you install extensions in VS Code?
  6. What is the purpose of hot reloading?
  7. How do you create a React application with create-react-app?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset