본문 바로가기
개념/React

React) object of useState

by kiseno 2025. 3. 26.
728x90
반응형
SMALL
import { useState } from 'react';

const ObjectOfUseState = () => {
    const [form, setForm] = useState({
        username: '',
        message: ''
    });

    // Corrected destructuring syntax
    const { username, message } = form;

    const onChange = e => {
        const nextForm = {
            ...form, // Spreads the existing form object
            [e.target.name]: e.target.value // Updates the changed field
        };
        setForm(nextForm);
    };

    const onClick = () => {
        alert(`${username}: ${message}`);
        setForm({
            username: '',
            message: ''
        });
    };

    const onKeyPress = e => {
        if (e.key === 'Enter') {
            onClick();
        }
    };

    return (
        <div>
            <h1>Event Practice</h1>
            <input
                type="text"
                name="username"
                placeholder="사용자 이름"
                value={username}
                onChange={onChange}
            />
            <input
                type="text"
                name="message"
                placeholder="아무거나 입력하세요"
                value={message}
                onChange={onChange}
                onKeyPress={onKeyPress}
            />
            <button onClick={onClick}>확인</button>
        </div>
    );
};

export default ObjectOfUseState;

### Component Explanation

1. **State Initialization**:
   ```jsx
   const [form, setForm] = useState({
       username: '',
       message: ''
   });
   ```
   - `useState` initializes `form` state as an object containing two fields: `username` and `message`, both initially set to empty strings.
   - `setForm` is the function provided by `useState` to update the state.

2. **State Destructuring**:
   ```jsx
   const { username, message } = form;
   ```
   - This line destructures the `username` and `message` properties from the `form` state object for easier access in the JSX and other operations.

3. **Event Handlers**:
   - **onChange Handler**:
     ```jsx
     const onChange = e => {
         const nextForm = {
             ...form, // Copies all existing form fields
             [e.target.name]: e.target.value // Updates the field changed
         };
         setForm(nextForm); // Sets the updated form object as the new state
     };
     ```
     - This function handles changes in both input fields. It uses a spread operator to copy the existing `form` object and updates the value of the field that was changed, determined by `e.target.name`.
     - This method ensures that the state updates are done immutably by creating a new object rather than mutating the existing state directly.

   - **onClick Handler**:
     ```jsx
     const onClick = () => {
         alert(`${username}: ${message}`); // Uses destructured state variables
         setForm({
             username: '',
             message: ''
         }); // Resets the form fields
     };
     ```
     - This function is triggered by the button click. It alerts the current values of `username` and `message`, then resets the `form` state to clear the inputs.

   - **onKeyPress Handler**:
     ```jsx
     const onKeyPress = e => {
         if (e.key === 'Enter') {
             onClick(); // Triggers the onClick function if Enter is pressed
         }
     };
     ```
     - This function listens for the "Enter" key press within the input fields. If "Enter" is pressed, it performs the same action as clicking the confirmation button, making form submission more user-friendly.

4. **Rendering**:
   ```jsx
   return (
       <div>
           <h1>Event Practice</h1>
           <input
               type="text"
               name="username"
               placeholder="사용자 이름"
               value={username}
               onChange={onChange}
           />
           <input
               type="text"
               name="message"
               placeholder="아무거나 입력하세요"
               value={message}
               onChange={onChange}
               onKeyPress={onKeyPress}
           />
           <button onClick={onClick}>확인</button>
       </div>
   );
   ```
   - The component returns a `div` containing a title, two input fields for `username` and `message`, and a button to submit the form.
   - Each input is a controlled component, with its value linked to the corresponding state property and handling changes via the `onChange` function. Additionally, `onKeyPress` is added to both inputs to handle submissions via the "Enter" key.

### Summary

This component effectively uses modern React practices with functional components and hooks. It demonstrates handling multiple controlled inputs with a single state object and using event handlers to update and reset state immutably. The use of event handlers for both clicking and key pressing makes the component responsive and user-friendly. This pattern is excellent for managing forms with multiple fields in React applications.

728x90
반응형
LIST

'개념 > React' 카테고리의 다른 글

React) function style of Component  (0) 2025.03.28
React) Handle To Input  (0) 2025.03.27
React) onChange Event  (0) 2025.03.25
React) state in input value  (0) 2025.03.24
React) onKeyPress Event handling  (0) 2025.03.23