Use Object List in State in React Functional Components

This project will demonstrate how to Use Object List in State in React Functional Components

  • ReactFunctionalComponents
    • public
      • images
        • thumb1.png
        • thumb2.png
        • thumb3.png
    • src
      • App.css
      • App.js
      • index.js
table, tr, th, td {
    border: 1px solid black;
}
          
import React, { useState } from 'react';

import "./App.css";

function App() {

    let [products, setProducts] = useState([
        {
            id: 'p01',
            name: 'name 1',
            price: 5,
            quantity: 6,
            status: true,
            photo: 'thumb1.gif'
        },
        {
            id: 'p02',
            name: 'name 2',
            price: 2,
            quantity: 3,
            status: false,
            photo: 'thumb2.gif'
        },
        {
            id: 'p03',
            name: 'name 3',
            price: 15,
            quantity: 16,
            status: true,
            photo: 'thumb3.gif'
        }
    ]);

    const changeValue = () => {
        // Update product 1
        products[1].name = 'wwwww';
        products[1].photo = 'thumb3.gif';

        // Update product 2
        products[2].price = 66;
        products[2].status = false;

        setProducts([...products]);
    }

    return (
        <div>
            <h3>Product List</h3>
            <table>
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Status</th>
                        <th>Price</th>
                        <th>Photo</th>
                    </tr>
                </thead>
                <tbody>
                    {products.map((product, index) => {
                        return <Tr key={index} product={product} index={index} />
                    })}
                </tbody>
            </table>
            <br />
            <input type="button" value="Change Value" onClick={changeValue} />
        </div>
    );
};

let Tr = ({ product, index }) => {
    return (
        <tr>
            <td>{index}</td>
            <td>{product.id}</td>
            <td>{product.name}</td>
            <td>{product.status ? 'show' : 'hide'}</td>
            <td>{product.price}</td>
            <td>
            <Image name={product.photo} width="120" />
            </td>
        </tr>
    );
};

let Image = ({ name, width }) => {
    return (
        <img src={'./images/' + name} width={width} />
    );
}

export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

Screenshots