Reader small image

You're reading from  Full Stack Development with Spring Boot and React - Third Edition

Product typeBook
Published inApr 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781801816786
Edition3rd Edition
Languages
Right arrow
Author (1)
Juha Hinkula
Juha Hinkula
author image
Juha Hinkula

Juha Hinkula is a software development lecturer at Haaga-Helia University of Applied Sciences in Finland. He received an MSc degree in Computer Science from the University of Helsinki and he has over 17 years of industry experience in software development. Over the past few years, he has focused on modern full stack development. He is also a passionate mobile developer with Android-native technology, and also uses React Native.
Read more about Juha Hinkula

Right arrow

Chapter 7: Getting Started with React

This chapter describes the basics of React programming. We will cover the skills that are required to create basic functionalities for the React frontend. In JavaScript, we use the ECMAScript 2015 (ES6) syntax because it provides many features that make coding cleaner.

In this chapter, we will look at the following topics:

  • How to create React components
  • Useful ES6 features
  • JavaScript XML (JSX) and styling
  • Properties (props) and state
  • Stateless components
  • Conditional rendering
  • React hooks
  • Custom hooks
  • The Context application programming interface (API)
  • Handling lists with React
  • Handling events with React
  • Handling forms with React

Technical requirements

In this book, we will be using the Windows operating system (OS), but all of the tools can be used with Linux and macOS as well. For our work with React hooks, React version 16.8 or higher will be required.

You can find more resources at the GitHub link at https://github.com/PacktPublishing/Full-Stack-Development-with-Spring-Boot-and-React/tree/main/Chapter07.

How to create React components

According to Meta Platforms, Inc., React is a JavaScript library for user interfaces (UIs). Since version 15, React has been developed under the Massachusetts Institute of Technology (MIT) license. React is component-based, and the components are independent and reusable. The components are the basic building blocks of React. When you start to develop a UI with React, it is good to start by creating mock interfaces. That way, it will be easy to identify what kinds of components you have to create and how they interact.

From the following screenshot of the mock UI, we can see how the UI can be split into components. In this case, there will be an application root component, a search bar component, a table component, and a table row component:

Figure 7.1 – React components

The components can then be arranged in a tree hierarchy, as shown in the following screenshot. The root component has two child components: the search...

Useful ES6 features

ES6 was released in 2015, and it introduced a lot of new features. ECMAScript is a standardized scripting language, and JavaScript is one implementation of it. In this section, we will go through the most important features released in ES6 that we will be using in the following sections.

Constants and variables

Constants, or immutable variables, can be defined by using a const keyword, as shown in the following code snippet. When using the const keyword, the variable content cannot be reassigned:

const PI = 3.14159;

Now, you will get an error if you try to reassign the PI value, as indicated in the following screenshot:

Figure 7.4 – Assignment to constant variable

The scope of const is block-scoped. This means that the const variable can only be used inside the block in which it is defined. In practice, the block is the area between curly brackets {}. The following sample code shows how the scope works:

let count =...

JSX and styling

JSX is the syntax extension for JavaScript. It is not mandatory to use JSX with React, but there are some benefits that make development easier. JSX, for example, prevents injection attacks because all values are escaped in the JSX before they are rendered. The most useful feature is that you can embed JavaScript expressions in the JSX by wrapping it with curly brackets; this technique will be used a lot in the following chapters.

In the following example, we can access the component props when using JSX. Component props are covered in the next section:

function App() {
  return <h1>Hello World {props.user}</h1>;
}

You can also pass a JavaScript expression as props, as shown in the following code snippet:

<Hello count={2+2} />

JSX is compiled into regular JavaScript by Babel.

You can use both internal and external styling with React JSX elements. Here are two examples of inline styling. This first one defines the style inside...

Props and state

Props and state are the input data for rendering the component. The component is re-rendered when the props or the state change.

Props

Props are inputs to components, and they are a mechanism to pass data from the parent component to its child component. Props are JavaScript objects, therefore they can contain multiple key-value pairs.

Props are immutable, so a component cannot change its props. Props are received from the parent component. A component can access props through the props object that is passed to the function component as a parameter. For example, let's take a look at the following component:

function Hello() {
  return <h1>Hello John</h1>;
}

The component is just rendering a static message, and it is not reusable. Instead of using a hardcoded name, we can pass a name to the Hello component by using props, like this:

function Hello(props) {
  return <h1>Hello {props.user}</h1>;
}

The...

Stateless components

The React stateless component is just a pure JavaScript function that takes props as an argument and returns a React element. Here's an example of a stateless component:

function HeaderText(props) {
  return (
    <h1>
      {props.text}
    </h1>
  )
}
export default HeaderText;

Our HeaderText example component is also called a pure component. A component is said to be pure if its return value is consistently the same given the same input values. React provides React.memo(), which optimizes the performance of pure functional components. In the following code snippet, we wrap our component using memo():

import React, { memo }  from  'react';
function HeaderText(props) {
  return (
    <h1>
      {props.text}
    </h1>
  ...

Conditional rendering

You can use a conditional statement to render different UIs if a condition is true or false. This feature can be used, for example, to show or hide some elements, handle authentication, and so on.

In the following example, we will check if props.isLoggedin is true. If so, we will render the <Logout /> component; otherwise, we render the <Login /> component. This is now implemented using two separate return statements:

function MyComponent(props) {
  const isLoggedin = props.isLoggedin;
  if (isLoggedin) {
    return (
      <Logout />
    )
  }
  
  return (
    <Login />
  )  
}

You can also implement this by using condition ? true : false logical operators, and then you need only one return statement, as illustrated here:

function MyComponent(props) {
  const...

React hooks

There are certain important rules for using hooks in React. You should always call hooks at the top level in your React function component. You shouldn't call hooks inside loops, conditional statements, or nested functions.

useState

We are already familiar with the useState hooks function that was used to declare states. Let's create one more example of using the useState hook. We will create a counter example that contains a button, and when it is pressed, the counter is increased by 1, as illustrated in the following screenshot:

Figure 7.6 – Counter component

First, we create a Counter component and declare a state called count with the initial value 0. The value of the counter state can be updated using the setCount function. The code is illustrated in the following snippet:

import React, { useState } from 'react';
function Counter() {
  // count state with initial value 0 
  const [count...

Custom hooks

You can also build your own hooks in React. Hooks' names should start with the use- word, and they are JavaScript functions. Custom hooks can also call other hooks. With custom hooks, you can reduce your component code complexity.

Let's go through a simple example of creating a custom hook. We will create a useTitle hook that can be used to update a document title. We will define it in its own file called useTitle.js. First, we define a function, and it gets one argument named title. The code is illustrated in the following snippet:

// useTitle.js
function useTitle(title) {
}

Next, we will use a useEffect hook to update the document title each time the title argument is changed, as follows:

import { useEffect } from 'react';
function useTitle(title) {
  useEffect(() => {
    document.title = title;
  }, [title]);
}
export default useTitle;

Now, we can start to use our custom hook. Let's...

The Context API

Passing data using props can be cumbersome if your component tree is deep and complex. You have to pass data through all components down the component tree. The Context API solves this problem, and it is recommended to use for global data that you might need in multiple components through your component tree—for example, a theme or authenticated user.

Context is created using the createContext method and it takes an argument that defines the default value. You can create your own file for the context, and the code looks like this:

import React from 'react';
const AuthContext = React.createContext('');
export default AuthContext;

Next, we will use a context provider component that makes our context available for other components. The context provider component has a value prop that will be passed to consuming components. In the following example, we have wrapped <MyComponent /> using the context provider component, therefore...

Handling lists with React

For list handling, we will learn about a new JavaScript map()method, which is useful when you have to manipulate a list. The map() method creates a new array containing the results of calling a function to each element in the original array. In the following example, each array element is multiplied by 2:

const arr = [1, 2, 3, 4];
const resArr = arr.map(x => x * 2); // resArr = [2, 4, 6, 8]

The map() method also has index as a second argument, which is useful when handling lists in React. List items in React need a unique key that is used to detect rows that have been updated, added, or deleted.

The following example code demonstrates a component that transforms an array of integers to an array of list items and renders these inside the ul element:

import React from 'react';
function MyList() {
  const data = [1, 2, 3, 4, 5];
  
  return (
    <div>
     ...

Handling events with React

Event handling in React is similar to handling DOM element events. The difference compared to HTML event handling is that event naming uses camelCase in React. The following sample component code adds an event listener to a button and shows an alert message when the button is pressed:

import React from 'react';
function MyComponent() {
  // This is called when the button is pressed 
  const buttonPressed = () => {
    alert('Button pressed');
  }
  return (
    <div>
      <button onClick={buttonPressed}>Press Me</button>
    </div>
  );
};
export default MyComponent;

In React, you cannot return false from the event handler to prevent the default behavior. Instead, you should call the preventDefault() method. In the following example, we are using a form element, and...

Handling forms with React

Form handling is a little bit different with React. An HTML form will navigate to the next page when it is submitted. Oftentimes, we want to invoke a JavaScript function that has access to form data after submission and avoid navigating to the next page. We already covered how to avoid submission in the previous section using preventDefault().

Let's first create a minimalistic form with one input field and a Submit button. In order to get the value of the input field, we use the onChange event handler. We use the useState hook to create a state variable called text. When the value of the input field is changed, the new value will be saved to the state. This is also called a controlled component because form data is handled by React.

The setText(event.target.value) statement gets the value from the input field and saves it to the state. Finally, we will show the typed value when a user presses the Submit button. Here is the source code for our first...

Summary

In this chapter, we started to learn about React, which we will be using to build our frontend. Before starting to develop with React, we covered the basics, such as the React component, JSX, props, the state, and hooks. In our frontend development, we used ES6, which makes our code cleaner. We then went through the features we need for further development. We also learned how to handle forms and events with React.

In the next chapter, we will focus on networking with React. We will also be using the GitHub REpresentational State Transfer (REST) API to learn how to consume a RESTful web service with React.

Questions

  1. What is a React component?
  2. What are state and props?
  3. How does data flow in a React app?
  4. What is the difference between stateless and stateful components?
  5. What is JSX?
  6. What are component life cycle methods?
  7. How should we handle events in React?
  8. How should we handle forms in React?

Further reading

Packt has the following great resources for learning about React:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Development with Spring Boot and React - Third Edition
Published in: Apr 2022Publisher: PacktISBN-13: 9781801816786
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Juha Hinkula

Juha Hinkula is a software development lecturer at Haaga-Helia University of Applied Sciences in Finland. He received an MSc degree in Computer Science from the University of Helsinki and he has over 17 years of industry experience in software development. Over the past few years, he has focused on modern full stack development. He is also a passionate mobile developer with Android-native technology, and also uses React Native.
Read more about Juha Hinkula