Reader small image

You're reading from  Modern API Development with Spring 6 and Spring Boot 3 - Second Edition

Product typeBook
Published inSep 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804613276
Edition2nd Edition
Languages
Concepts
Right arrow
Author (1)
Sourabh Sharma
Sourabh Sharma
author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma

Right arrow

Designing a User Interface

In the previous chapter, you implemented authentication and authorization using Spring Security; that chapter also included all the example e-commerce app APIs. In this chapter, you will develop the frontend of an example e-commerce app using the React library. This UI app will then consume the APIs developed in the previous chapter, Chapter 6, Securing REST Endpoints Using Authorization and Authentication. This UI app will be a single-page application (SPA) that consists of interactive components such as Login, Product Listing, Product Detail, Cart, and Order Listing. This chapter will conclude the end-to-end development and communication between different layers of an online shopping app. By the end of this chapter, you will have learned about SPAs, UI component development using React, and consuming the REST APIs using the browser’s built-in Fetch API.

This chapter will cover the following topics:

  • Learning React fundamentals
  • Exploring...

Technical requirements

You need the following prerequisites for developing and executing the code:

  • You should be familiar with JavaScript: data types, variables, functions, loops, and array methods such as map(), Promises, and async, and so on.
  • Node.js 18.x with Node Package Manager (npm) 9.x (and optionally, Yarn, which you can install using npm install yarn -g).
  • Visual Studio Code (VS Code): This is a free source code editor. You can use any other source code editor of your choice.
  • React 18 libraries that will be included when you use create-react-app.

Let’s get the ball rolling!

Please visit the following link to check the code for this chapter:

https://github.com/PacktPublishing/Modern-API-Development-with-Spring-6-and-Spring-Boot-3/tree/main/Chapter07

Learning React fundamentals

React is a declarative library used to build interactive and dynamic UIs, including isolated small components. It is also sometimes referred to as a framework because it is as capable as and comparable with other JavaScript frameworks such as AngularJS. However, React is a library and works with other supported libraries, including React Router, React Redux, and so on. You normally use it to develop SPAs, but it can also be used to develop full stack applications.

React is used to build the view layer of the application per the MVC architecture. You can build reusable UI components with their own state. You can use either plain JavaScript with HTML or JavaScript Syntax Extension (JSX) for templating. We’ll be using JSX in this chapter, which employs a virtual Document Object Model (VDOM) for dynamic changes and interactions.

Let’s create a new React app using the create-react-app utility next. This utility scaffolds and provides the basic...

Exploring React components and other features

Each page in an app is built up using React components — for example, the Product Listing page of Amazon can broadly be divided into Header, Footer, Content, Product List, Filter and Sorting options, and Product Card components. You can create components in React in two ways: by using JavaScript classes or functions.

Let’s create an example header component in React with both a function and a class.

You can either write a plain old JavaScript function or an ECMAScript 6 (ES6) arrow function. Components created using either arrow functions or plain JavaScript functions are called React functional components. We’ll mostly use functional components in our code. In the following code snippet, check out the Header component using a JavaScript arrow function:

export default const Header = (props) => {  return (
    <div>
      <h1>{props.title...

Designing the e-commerce app components

Design is not only a key part of UX and UI work, but is also important for frontend developers. Based on the design, you can create reusable and maintainable components. Our example e-commerce app is a simple application that does not need much attention. You will create the following components in this application:

  • Product listing component: A component that displays all the products and acts as a home page. Each product in the list will be displayed as a card with the product name, price, and two buttons—Buy now and Add to bag. The following screenshot displays the Product listing page, which shows the product information along with an image of each product:
Figure 7.3 – Product listing page (home page)

Figure 7.3 – Product listing page (home page)

  • Product detail component: This component displays the details of a product when clicked. It displays the product image, product name, product description, tags, and the Buy now and...

Consuming APIs using Fetch

Let’s create the first component — that is, the Product Listing page. Create a new file in the src/components directory with the name ProductList.js. This is the parent component of the Product Listing page.

This component fetches the products from the backend server and passes them to the child component, Products (it creates a new Products.js file under the src/components directory).

Products contains the logic responsible for looping through the fetched product list. Each iteration renders the card UI of each product. This product card component is represented using ProductCard, another component. Therefore, let’s create a ProductCard.js file, under src/components.

You can write the product card code inside products (product list component), but to single out the responsibilities, it’s better to create a new component.

The ProductCard component has a Buy now button and an Add to bag link. These links should only...

Implementing authentication

Before you jump into the Login component development, you will want to figure out how to manage a token received from a successful login response and how to make sure that if the access token has expired, then a refresh token request should be fired before making any call that requires authentication.

The browser allows you to store tokens or any other information in cookies, session storage, and local storage. From the server side, we haven’t opted for cookie or stateful communication, therefore we are left with the remaining two options. Session storage is preferable for more secure applications because it is specific to a given tab, and it gets cleared as soon as you click on the Refresh button or close the tab. We want to manage login persistence between different tabs and page refresh; therefore, we’ll opt for local storage of the browser.

On top of that, you can also store them in the state in the same way you will manage the cart...

Running the application

You need a backend server for testing the UI because the UI fires REST APIs to get the data. You are going to use code from Chapter 6.

Go to the home directory of the Chapter 6 code. You can build the code by running gradlew clean build from the root of the Chapter06 project and run the backend using the following command:

$ java -jar build/libs/Chapter06-0.0.1-SNAPSHOT.jar.

Make sure to use Java 17 in the path.

Once the backend is up and running, you can open another terminal and start the ecomm-ui app by executing the following command from the Chapter07/ecomm project root directory:

$ yarn start

If the application starts successfully, the UI will be accessible at http://localhost:3000. You can open http://localhost:3000 in your favorite browser.

Once the product listing page loads, you can log in to the example e-commerce UI app with the username/password (scott/tiger) and perform all the operations such as checkout, orders, and so on.

...

Summary

In this chapter, you have learned some basic concepts of React and created different types of components using them. You have also learned how to use the browser’s built-in Fetch API to consume the REST APIs. You acquired the following skills in React: developing a component-based UI, implementing routing, consuming REST APIs, implementing functional components with hooks, writing custom hooks, and building a global state store with a React context API and a useReducer hook.

The concepts and skills you acquired in this chapter have laid a solid foundation for modern frontend development and advance you toward gaining a 360-degree perspective of application development.

In the next chapter, you will learn about writing automated tests for REST-based web services.

Questions

  1. What is the difference between props and state?
  2. What is an event and how can you bind events in a React component?
  3. What is a higher-order component?

Answers

  1. Props are special objects that you use to pass the values/objects/functions from the parent component to a child component, whereas state belongs to a component – it could be global or local to the component. From a functional component perspective, you use the useState hook for local state and useContext for global state.
  2. In general, events are objects generated by the browser on input such as keydown or onclick. React uses SyntheticEvent to ensure that the browser’s native events work identically across all browsers. SyntheticEvent wraps on top of the native event. You used the onChange={(e) => setUserName(e.target.value)} code in the login component. Here, e is SyntheticEvent and target is one of its attributes. The onChange event is bound in JSX that calls setUserName when the input value is changed. You can also use the same JavaScript technique to bind events such as window. addEventListener("click", handleClick).

Ideally, you...

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern API Development with Spring 6 and Spring Boot 3 - Second Edition
Published in: Sep 2023Publisher: PacktISBN-13: 9781804613276
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
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma