React technical principles and code development practice: use React to develop a shopping cart application

1. Background Introduction

An indispensable function before a shopping website or e-commerce platform goes online is the “shopping cart”. This article will lead readers to fully understand the application of React technology in shopping carts through a shopping cart application case developed based on the React framework. We can start with the following points to introduce:

1. Introduction to React technology: React is an open source front-end JavaScript framework launched by Facebook. It is a JavaScript library for building user interfaces. React makes it easy to write complex view layer components and reusable modules and assemble them into complex applications. React mainly focuses on the UI layer, so it is not only suitable for web development, but also for mobile and native application development.

2. Features of React:

⒈ Virtual DOM (Virtual DOM): React uses Virtual DOM as a programming model, which means that the synchronization between the view and the real DOM only takes a moment, so React can re-render the application in a short time.

2. Modularization: React uses JSX syntax to create components. React components are usually independent and complete. The outside world can only access their output status and behavior, but cannot directly modify internal data or status. Doing this makes the code cleaner and easier to maintain.

⒊ Declarative programming: React is a declarative programming language. Users only need to describe the appearance of the application, and React is responsible for updating and rendering the interface without manually operating DOM nodes.

3. Shopping cart application requirements analysis: The shopping cart application is a typical multi-page application, among which the most important page is the shopping cart page. The shopping cart page should have the following basic requirements:

1) Visually display the products and quantities purchased by users;

2) Support the addition, deletion, modification and search operations of products;

3) Able to record the user’s shipping address and payment information;

4) Provide coupons and points deduction functions;

5) Users can choose the logistics delivery method;

6) Users can choose the order review rating;

2. Core concepts and connections

Below we introduce some of the main concepts and related terms involved in React.

JSX

JSX (JavaScript XML) is a JS extension syntax used to describe HTML elements. JavaScript expressions can be embedded in JSX. For example, the following code snippet uses JSX syntax:

const name = 'John';

const element = <h1>Hello, {name}</h1>;

 ReactDOM.render(
   element,
   document.getElementById('root')
 );

JSX will be compiled into pure JavaScript code similar to the following:

const name = 'John';

const element = React.createElement(
  'h1',
  null,
  `Hello, ${name}`
);

ReactDOM.render(element, document.getElementById('root'));

The React createElement() function is used to generate virtual DOM nodes.

Virtual DOM

Virtual DOM is a programming model in which the data structures are actually JavaScript objects. When the state changes, React will recalculate the virtual DOM of the entire component tree, then compare the differences between the two trees, and then update the actual DOM. This calculation process is more efficient than the traditional Diff algorithm.

Component

Component is the basic unit of React. It is a function or class that returns a JavaScript object that describes the properties, status, subcomponents, etc. that the current UI fragment should have. React treats components as minimized instances rather than one large class, and can be nested and composed.

Props and State

Props is how parent components pass data to child components, and State is how the component itself saves state. State triggers UI updates when changed within the component, and Props remain unchanged after the parent component is passed to the child component.

Life Cycle

Life Cycle is a state machine provided by React to manage the life cycle of components. Including componentWillMount(), componentDidMount(), shouldComponentUpdate(), componentDidUpdate(), componentWillUnmount() and so on. These methods provide powerful control capabilities, allowing us to execute some of the code logic we want at different stages.

3. Detailed explanation of core algorithm principles, specific operation steps, and mathematical model formulas

First, let’s define several functions that the shopping cart page should have:

1) Display the purchased products and their quantities;

2) Add, delete, modify purchased items and their quantities;

3) Enter the shipping address and payment information;

4) Choose the logistics and delivery method;

5) Select the order evaluation level;

According to the above five functional points, we can divide the shopping cart page into the following components:

1) Cart: Shopping cart component, which displays the products and their quantities that the user has added to the shopping cart, and supports addition, deletion, modification and query operations of products.

2) AddressForm: Shipping address form component, enter the user’s shipping address and other information, such as mobile phone number, email, etc.

3) PaymentForm: Payment method form component, which provides corresponding payment information filling methods according to the payment method selected by the user.

4) DeliveryMethod: Delivery method selection component, allowing users to select freight express and free shipping options.

5) OrderComment: Order comment component, allowing users to evaluate orders, such as ratings and text comments.

Next, we implement each component according to the design pattern of React components.

Cart component

The function of the Cart component is to display the products and their quantities that the user has added to the shopping cart, and to support the addition, deletion, modification and query operations of products.

Data storage form

In order to facilitate data management, the Cart component uses two arrays to store shopping cart product information, namely cartItems and totalPrice.

class Cart extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      cartItems: [],
      totalPrice: 0,
    };
  }

  // The definitions of componentDidMount(), shouldComponentUpdate() and componentWillUnmount() methods are omitted here

  render(){
    const { cartItems, totalPrice } = this.state;

    return (
      <div className="cart">
        {/* Omitted here */}
        {
          cartItems.map((item, index) =>
            <div key={index} className="cartItem">
              <span>{item.title}</span>
              <span>${item.price}</span>
              <button onClick={() => this.removeItem(index)}>Remove</button>
              <input type="number" value={item.count} onChange={(e) => this.updateCount(index, e.target.value)}/>
            </div>
          )
        }
        {/* Omitted here */}
      </div>
    );
  }

  removeItem(index) {
    let newCartItems = [...this.state.cartItems];
    newCartItems.splice(index, 1);
    this.setState({
      cartItems: newCartItems,
      totalPrice: parseFloat(newCartItems.reduce((acc, cur) => acc + (cur.price * cur.count), 0).toFixed(2))
    });
  }

  updateCount(index, count) {
    if (!isNaN(parseInt(count))) {
      let newCartItems = [...this.state.cartItems];
      newCartItems[index].count = parseInt(count);
      this.setState({
        cartItems: newCartItems,
        totalPrice: parseFloat(newCartItems.reduce((acc, cur) => acc + (cur.price * cur.count), 0).toFixed(2))
      });
    } else {
      alert("Please enter a valid number!");
    }
  }
}

Method function definition

The method functions of the Cart component are as follows:

  1. addItem(): This method is used to add items to the shopping cart. The parameter passed in is the product object to be added, in the format {id, title, price, image, count}.

  2. removeItem(): This method is used to remove the item at the specified position from the shopping cart. The parameter passed in is the index value of the item to be removed in the array.

  3. updateCount(): This method is used to update the number of items at the specified position in the shopping cart. The parameters passed in are the index value and new quantity value of the item to be updated in the array. If the passed in quantity value is NaN, a prompt box will pop up.

  4. calculateTotalPrice(): This method is used to calculate the total price of all items in the current shopping cart. The returned result is a floating point price string.

Usage scenario example

Suppose there is a shopping cart instance object cart. You can add, remove, and modify items to the shopping cart by calling the addItem(), removeItem(), and updateCount() methods of the instance object. For example:

cart.addItem(myBook);

// modify the book quantity to 3
cart.updateCount(0, 3);

//delete the first item in the cart
cart.removeItem(0);

AddressForm component

The function of the AddressForm component is to enter the user’s shipping address and other information, such as mobile phone number, email address, etc.

Data storage form

The AddressForm component has no explicit state variables, but uses useState() hook internally to store the delivery address information.

import React, { useState } from "react";

function AddressForm(props) {
  const [address, setAddress] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");

  // The definition of the render() method is omitted here

  function handleSubmit(event) {
    event.preventDefault();
    props.onSubmit(address, phone, email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="address">Address:</label>
      <br />
      <textarea rows="4" cols="50" id="address" placeholder="Street address, P.O. box, company name, c/o"
        value={address} onChange={(e) => setAddress(e.target.value)} required></textarea>

      <br /><br />

      <label htmlFor="phone">Phone Number:</label>
      <br />
      <input type="text" id="phone" placeholder="(123) 456-7890" value={phone} onChange={(e) => setPhone(e.target.value)} pattern="[0- 9]{3}\s?\d{3}\-\d{4}" required />

      <br /><br />

      <label htmlFor="email">Email:</label>
      <br />
      <input type="email" id="email" placeholder="<EMAIL>" value={email} onChange={(e) => setEmail(e.target.value)} required />

      <br /><br />

      <button type="submit">Confirm and Continue</button>
    </form>
  );
}

export default AddressForm;

Method function definition

The method functions of the AddressForm component are as follows:

  1. handleChange(): This method is used to process input events, mainly saving the input content in the corresponding state variable.

  2. handleSubmit(): This method is used to handle submission events. It mainly calls the onSubmit() method passed in by the parent component and passes in the address, mobile phone number and email information.

Usage scenario example

Suppose there is an instance object addressForm of the AddressForm component. You can obtain the user’s input by calling the handleChange() and handleSubmit() methods of the instance object. For example:

function onAddressSubmitted(address, phone, email) {
  console.log(`Your address is ${address}, phone number is ${phone}, email is ${email}`);
}

<AddressForm onSubmit={onAddressSubmitted}/>