Understanding React Components: Product, Order, Inventory

React, a popular JavaScript library developed by Facebook, revolutionizes the way we build user interfaces. At the heart of React's architecture are components. Components are reusable, self-contained pieces of UI that make it easy to develop complex applications by breaking them into smaller, manageable pieces.

In this blog, we'll dive into React components, using a practical example involving product, order, and inventory services to illustrate their use. We'll cover functional components, class components, props, state, and how to compose these components to build a robust application.

Introduction

React components come in two flavors.

  • Functional Components: These are simple JavaScript functions that receive props as arguments and return React elements.
  • Class Components: These are ES6 classes that extend from React.Component and have additional features such as local state and lifecycle methods.

With the introduction of Hooks in React 16.8, functional components can now use state and other features previously exclusive to class components.

Building the Services Example

Let's create a small application that involves products, orders, and inventory services. We will build the following components.

  1. ProductList: Displays a list of products.
  2. OrderForm: Allows users to place an order.
  3. InventoryStatus: Shows the current inventory status.

We'll start by setting up our project structure and then dive into each component with code snippets and explanations.

Project Structure

Here's a simplified structure for our project.

/src
  /components
    ProductList.js
    OrderForm.js
    InventoryStatus.js
  App.js
  index.js

ProductList Component

The ProductList component displays a list of products. We'll use a functional component for this example.

ProductList.js

import React from 'react';

// Functional Component
const ProductList = ({ products, onSelectProduct }) => {
    return (
        <div>
            <h1>Product List</h1>
            <ul>
                {products.map(product => (
                    <li key={product.id} onClick={() => onSelectProduct(product)}>
                        <h2>{product.name}</h2>
                        <p>Price: ${product.price}</p>
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default ProductList;

Explanation

  • The ProductList component receives products and onSelectProduct as props.
  • It maps through the product array and displays each product's name and price.
  • The onSelectProduct function is called when a product is clicked, allowing us to handle product selection.

OrderForm Component

The OrderForm component lets users place an order by selecting a product and entering the quantity.

OrderForm.js

import React, { useState } from 'react';
// Functional Component with Hooks
const OrderForm = ({ selectedProduct, onOrderSubmit }) => {
    const [quantity, setQuantity] = useState(1);
    const handleQuantityChange = (event) => {
        setQuantity(event.target.value);
    };
    const handleSubmit = (event) => {
        event.preventDefault();
        onOrderSubmit(selectedProduct, quantity);
    };
    return (
        <div>
            <h1>Order Form</h1>
            {selectedProduct ? (
                <form onSubmit={handleSubmit}>
                    <h2>Product: {selectedProduct.name}</h2>
                    <label>
                        Quantity:
                        <input
                            type="number"
                            value={quantity}
                            onChange={handleQuantityChange}
                            min="1"
                        />
                    </label>
                    <button type="submit">Place Order</button>
                </form>
            ) : (
                <p>Please select a product to order.</p>
            )}
        </div>
    );
};
export default OrderForm;

Explanation

  • The OrderForm component uses the useState hook to manage the quantity state.
  • The handleQuantityChange function updates the quantity according to the user type.
  • The handleSubmit function prevents the default form submission and calls onOrderSubmit with the selected product and quantity.

InventoryStatus Component

The inventory status component shows the inventory status of the selected product.

InventoryStatus.js

import React from 'react';

// Functional Component
const InventoryStatus = ({ product, inventory }) => {
    const inventoryCount = inventory[product.id] || 0;
    return (
        <div>
            <h1>Inventory Status</h1>
            {product ? (
                <div>
                    <h2>Product: {product.name}</h2>
                    <p>Available Inventory: {inventoryCount}</p>
                </div>
            ) : (
                <p>Select a product to see its inventory status.</p>
            )}
        </div>
    );
};
export default InventoryStatus;

Explanation

  • The inventory status component receives the product and inventory as props.
  • It looks up the inventory count for the selected product and displays it.

Putting it all together in the App Component

App.js

import React, { useState } from 'react';
import ProductList from './components/ProductList';
import OrderForm from './components/OrderForm';
import InventoryStatus from './components/InventoryStatus';
const App = () => {
    const [selectedProduct, setSelectedProduct] = useState(null);
    const [orders, setOrders] = useState([]);
    const [inventory, setInventory] = useState({
        1: 100,
        2: 50,
        3: 25
    });
    const products = [
        { id: 1, name: 'Product A', price: 10 },
        { id: 2, name: 'Product B', price: 20 },
        { id: 3, name: 'Product C', price: 30 }
    ];
    const handleProductSelect = (product) => {
        setSelectedProduct(product);
    };
    const handleOrderSubmit = (product, quantity) => {
        setOrders([...orders, { product, quantity }]);
        setInventory({
            ...inventory,
            [product.id]: inventory[product.id] - quantity
        });
        setSelectedProduct(null);
    };
    return (
        <div>
            <ProductList products={products} onSelectProduct={handleProductSelect} />
            <OrderForm selectedProduct={selectedProduct} onOrderSubmit={handleOrderSubmit} />
            <InventoryStatus product={selectedProduct} inventory={inventory} />
        </div>
    );
};
export default App;

Explanation

  • The App component maintains the state for selected products, orders, and inventory.
  • It provides a list of products and functions to handle product selection and order submission.
  • The handleProductSelect function updates the selected product.
  • The handleOrderSubmit function adds the order to the list, updates the inventory, and clears the selected product.

Conclusion

React components are the building blocks of a React application. They allow you to encapsulate UI logic and manage the state effectively. By using functional components and hooks, you can create clean and reusable components. In our example, we built a simple application with ProductList, OrderForm, and InventoryStatus components to manage products, orders, and inventory. Understanding and leveraging React components effectively can greatly enhance your ability to build scalable and maintainable applications.