DEV Community

Faisal Ahmed
Faisal Ahmed

Posted on

User Form in one state(object) in React

import React, {useState} from 'react'

const User = () => {

    const [user, setUser] = useState({name: '', age: ''});
    const {name, age} = user;

    const handleChange = (e) => {
        setUser({...user, [e.target.name] : e.target.value});
    }

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(user);
    }
    return (
        <div>
            <h2>User</h2>

            <form onSubmit={handleSubmit}>
                <input name='name' value={name} onChange={handleChange} type="text" placeholder='enter name' />
                <input name='age' value={age} onChange={handleChange} type="number" placeholder='enter age' />
                <button type='submit'>Enter</button>
            </form>

        </div>
    )
}

export default User
Enter fullscreen mode Exit fullscreen mode

Top comments (0)