React Philosophy - Official Example

In this technical blog, we will introduce the official React example: React Philosophy. We'll dive into the core concepts of componentization, state management, and data flow used in this example. Let's get started together!

Project overview

React is a popular JavaScript library for building user interfaces. React's design philosophy is to build complex UI interfaces through componentization, making the code more modular, maintainable, and reusable.

In the React Philosophy example, we created a simple filterable table of products. This example involves the following components:

  1. FilterableProductTableComponent: As the container component of the entire application, it contains the search bar and product table components.
  2. SearchBarComponent: used to receive the search keywords and filter conditions entered by the user, and update the status of the parent component through the callback function.
  3. ProductTableComponent: display the product table, and filter according to the search keywords and filter conditions entered by the user.
  4. ProductCategoryRowComponent: Used to display product category rows in the product table.
  5. ProductRowComponent: Used to display each row of products in the product table.

FilterableProductTablecomponents

FilterableProductTableThe component is the container component of the whole application, the code is as follows:

import { useState } from 'react';

function FilterableProductTable({ products }) {
    const [filterText, setFilterText] = useState('');
    const [inStockOnly, setInStockOnly] = useState(false);

    return (
        <div>
            <SearchBar
                filterText={filterText}
                inStockOnly={inStockOnly}
                onFilterTextChange={setFilterText}
                onInStockOnlyChange={setInStockOnly} />
            <ProductTable
                products={products}
                filterText={filterText}
                inStockOnly={inStockOnly} />
        </div>
    );
}

FilterableProductTableThe component receives an productsarray as props representing the list of products to display. Inside FilterableProductTablethe component, we use useStatehooks to manage the status of the search key filterTextand whether to only show products that are in stock inStockOnly.

FilterableProductTableComponents contain SearchBarcomponents and ProductTablecomponents. propsCommunication between child components and parent components is achieved by passing state and handler functions to child components.

SearchBarcomponents

SearchBarThe component is used to receive the search keywords and filter conditions entered by the user, and update the state of the parent component through the callback function. code show as below:

function SearchBar({
    filterText,
    inStockOnly,
    onFilterTextChange,
    onInStockOnlyChange
}) {
    return (
        <form>
            <input
                type="text"
                value={filterText} placeholder="Search..."
                onChange={(e) => onFilterTextChange(e.target.value)} />
            <label>
                <input
                    type="checkbox"
                    checked={inStockOnly}
                    onChange={(e) => onInStockOnlyChange(e.target.checked)} />
                {' '}
                Only show products in stock
            </label>
        </form>
    );
}

SearchBarThe component receives filterTextand inStockOnlyas props the current search keyword and the status of whether to only show products in stock. At the same time, it also receives two callback functions onFilterTextChangeand onInStockOnlyChangeare used to update the state of the parent component when the user enters or selects a filter condition.

In SearchBarthe component's JSX, we use a text input box and a check box for entering search keywords and selecting whether to only display products in stock. Through onChangethe event handler function, the value entered by the user is passed to the parent component.

ProductTablecomponents

ProductTableThe component is used to display the product table and filter according to the search keywords and filter conditions entered by the user. code show as below:

function ProductTable({ products, filterText, inStockOnly }) {
    const rows = [];
    let lastCategory = null;

    products.forEach((product) => {
        if (
            product.name.toLowerCase().indexOf(
                filterText.toLowerCase()
            ) === -1
        ) {
            return;
        }
        if (inStockOnly && !product.stocked) {
            return;
        }
        if (product.category !== lastCategory) {
            rows.push(
                <ProductCategoryRow
                    category={product.category}
                    key={product.category} />
            );
        }
        rows.push(
            <ProductRow
                product={product}
                key={product.name} />
        );
        lastCategory = product.category;
    });

    return (
        <table>
            <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
            </tr>
            </thead>
            <tbody>{rows}</tbody>
        </table>
    );
}

ProductTableComponents receive productsarrays, filterTextand inStockOnlyas props. Inside ProductTablethe component, we filter the product list based on the search keywords and filter conditions entered by the user, and then generate the corresponding product table rows.

When traversing productsthe array, we first filter based on the search key, and if the name of the product does not contain the search key, the product is skipped. Next, filter based on whether only products in stock are displayed. If "Only display products in stock" is selected but the current product is not in stock, this product will also be skipped. Finally, according to the category of the product, it is judged whether a product category row needs to be added.

ProductCategoryRowComponents and ProductRowAssemblies

ProductCategoryRowComponent and ProductRowComponent are used to display the product category row and each row of products respectively in the products table. Their codes are as follows:

function ProductCategoryRow({ category }) {
    return (
        <tr>
            <th colSpan="2">
                {category}
            </th>
        </tr>
    );
}

function ProductRow({ product }) {
    const name = product.stocked ? product.name :
        <span style={
   
   { color: 'red' }}>
            {product.name}
        </span>;

    return (
        <tr>
            <td>{name}</td>
            <td>{product.price}</td>
        </tr>
    );
}

ProductCategoryRowThe component receives categoryas props representing the category name of the product. It adds a cell to the table that combines two columns to display the product category names.

ProductRowComponents receive productas props, information representing a single product. Depending on whether the product is in stock, we use conditional rendering to decide whether to add styles, and display different text colors based on the product name.

Logincomponents

Finally, we Loginimported the sample data in the component PRODUCTSand passed it to FilterableProductTablethe component as productsprops. code show as below:

const PRODUCTS = [
    { category: "Fruits", price: "$1", stocked: true, name: "Apple" },
    { category: "Fruits", price: "$1", stocked: true, name: "Dragonfruit" },
    { category: "Fruits", price: "$2", stocked: false, name: "Passionfruit" },
    { category: "Vegetables", price: "$2", stocked: true, name: "Spinach" },
    { category: "Vegetables", price: "$4", stocked: false, name: "Pumpkin" },
    { category: "Vegetables", price: "$1", stocked: true, name: "Peas" }
];

export default function Login() {
    return <FilterableProductTable products={PRODUCTS} />;
}

LoginThe component simply PRODUCTSpasses sample data to FilterableProductTablethe component, enabling the rendering of the entire application.

Effect:

 

 

Summarize

In this tech blog, we dig into the official React example: The React Philosophy. We learned core React concepts like componentization, state management, and data flow, and put them into practice with a simple example of a filterable product table.

Guess you like

Origin blog.csdn.net/weixin_60895836/article/details/132016063