Use Object in State in React Functional Components

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

  • ReactFunctionalComponents
    • src
      • App.js
      • index.js
import React, { useState } from 'react';

function App() {

    let [product, setProduct] = useState({
        id: 'p01',
        name: 'name 1',
        price: 5,
        quantity: 6,
        status: true,
        photo: 'thumb1.gif'
    });

    const changeValue = () => {
        product.name = 'abc';
        product.status = false;
        product.price = 8;
        product.photo = 'thumb2.gif';
        setProduct({...product, product});
    }

    return (
    <div>
        <h3>Product Info</h3>
        id: {product.id}
        <br />
        name: {product.name}
        <br />
        price: {product.price}
        <br />
        quantity: {product.quantity}
        <br />
        total: {product.price * product.quantity}
        <br />
        status: {product.status ? 'Show' : 'Hide'}
        <br />
        <img src={'./images/' + product.photo} width="120" />
        <br />
        <input type="button" value="Change Value" onClick={changeValue} />
    </div>
    );
};

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