Reader small image

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

Product typeBook
Published inOct 2023
PublisherPackt
ISBN-139781805122463
Edition4th Edition
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

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 our 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:

  • Creating React components
  • Useful ES6 features
  • JSX and styling
  • Props and state
  • Conditional rendering
  • React hooks
  • The Context API
  • Handling lists, events, and forms with React

Technical requirements

For our work, React version 18 or higher will be required. We set up our environment correctly in Chapter 7.

You can find more resources at the GitHub link for this chapter: https://github.com/PacktPublishing/Full-Stack-Development-with-Spring-Boot-3-and-React-Fourth-Edition/tree/main/Chapter08.

Creating React components

React is a JavaScript library for user interfaces (UIs). Since version 15, React has been developed under the MIT license. React is component-based, and the components are independent and reusable. 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 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 8.1: React components

The components can then be arranged in a tree hierarchy, as shown in the following screenshot:

Figure 7.2 – Component tree

Figure 8.2: Component tree

The root component has two child components: the search component and the table component. The table component has one child component...

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

Figure 8.4: Assignment to constant variable

The 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 {}. If const is defined outside of any function or block, it becomes a global variable, and you...

JSX and styling

JavaScript XML (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. For example, JSX prevents injection attacks because all values are escaped in JSX before they are rendered. The most useful feature is that you can embed JavaScript expressions in JSX by wrapping them with curly brackets; this technique will be used a lot in the following chapters. JSX is compiled into regular JavaScript by Babel.

In the following example, we can access a component’s props when using JSX:

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

Component props are covered in the next section.

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

<Hello count={2+2} />

You can use both inline and external styling with React JSX elements. Here are two examples of inline styling. This...

Props and state

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

Props

Props are inputs to components, and they are a mechanism to pass data from a parent component to its child component. Props are JavaScript objects, so 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 just renders 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 parent component can send...

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 isLoggedin = props.isLoggedin;
  return (
    <>
      { isLoggedin ? <Logout /> : <Login /> }
    </>
  );
}

React hooks

Hooks were introduced in React version 16.8. Hooks allow you to use state and some other React features in functional components. Before hooks, you had to write class components if states or complex component logic were needed.

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. Hook names begin with the word use, followed by the purpose they serve.

useState

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

Figure 8.6: Counter component

  1. First, we create a Counter component and declare a state called count...

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 for use with global data that you might need in multiple components throughout your component tree – for example, a theme or authenticated user.

Context is created using the createContext method, which 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, which 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...

Handling lists with React

For list handling, we will learn about the 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 on 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 following example code demonstrates a component that transforms an array of integers into 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 (
    <>
      <ul>
        {
        data.map((number) =>
          <li>Listitem {number}</li>)
        }
      </ul>
    </>
  );
};
export default MyList;

The following screenshot shows what the component looks like when it is rendered. If you open the console...

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:

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

As we learned earlier in the counter example, you have to pass a function to the event handler instead of calling it. Now, the handleClick function is defined outside the return statement, and we can refer to it using the function name:

// Correct
<button onClick={handleClick}>Press Me</button>
// Wrong
<button onClick={handleClick()}>Press Me</button>
...

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. In React, often, 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 component is called a controlled component because form data is handled by React. In an uncontrolled component, the form data is handled only by the DOM.

The setText(event.target.value) statement gets the value from the input field and saves it to the state. Finally, we will show the...

Summary

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

In the next chapter, we will focus on TypeScript with React. We will learn the basics of TypeScript and how to use it in our React projects.

Questions

  1. What is a React component?
  2. What are states 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. How are React hooks named?
  7. How does context work?

Further reading

Here are some other good resources for learning about React:

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask the author questions, and learn about new releases – follow the QR code below:

https://packt.link/FullStackSpringBootReact4e

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Development with Spring Boot 3 and React - Fourth Edition
Published in: Oct 2023Publisher: PacktISBN-13: 9781805122463
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 $15.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