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.

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.

Bash
/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

JavaScript
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

OrderForm Component

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

OrderForm.js

JavaScript
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

InventoryStatus Component

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

InventoryStatus.js

JavaScript
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

Putting it all together in the App Component

App.js

JavaScript
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

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.