import React, { useState } from 'react';
const ControlledInputs = () => {
const [firstName, setFirstName] = useState('');
const [email, setEmail] = useState('');
const [people, setPeople] = useState([]);
const handleSubmit = (e) => {
e.preventDefault();
if (firstName && email) {
const person = { id: new Date().getTime().toString(), firstName, email };
console.log(person);
setPeople((people) => {
return [...people, person];
});
setFirstName('');
setEmail('');
} else {
console.log('empty values');
}
};
return (
<>
<article>
<form className='form' onSubmit={handleSubmit}>
<div className='form-control'>
<label htmlFor='firstName'>Name : </label>
<input
type='text'
id='firstName'
name='firstName'
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</div>
<div className='form-control'>
<label htmlFor='email'>Email : </label>
<input
type='email'
id='email'
name='email'
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<button type='submit'>add person</button>
</form>
{people.map((person, index) => {
const { id, firstName, email } = person;
return (
<div className='item' key={id}>
<h4>{firstName}</h4>
<p>{email}</p>
</div>
);
})}
</article>
</>
);
};
export default ControlledInputs;
Multiple-inputs
import React, { useState } from 'react';
const ControlledInputs = () => {
const [person, setPerson] = useState({ firstName: '', email: '', age: '' });
const [people, setPeople] = useState([]);
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setPerson({ ...person, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
if (person.firstName && person.email && person.age) {
const newPerson = { ...person, id: new Date().getTime().toString() };
setPeople([...people, newPerson]);
setPerson({ firstName: '', email: '', age: '' });
}
};
return (
<>
<article className='form'>
<form>
<div className='form-control'>
<label htmlFor='firstName'>Name : </label>
<input
type='text'
id='firstName'
name='firstName'
value={person.firstName}
onChange={handleChange}
/>
</div>
<div className='form-control'>
<label htmlFor='email'>Email : </label>
<input
type='email'
id='email'
name='email'
value={person.email}
onChange={handleChange}
/>
</div>
<div className='form-control'>
<label htmlFor='age'>Age : </label>
<input
type='number'
id='age'
name='age'
value={person.age}
onChange={handleChange}
/>
</div>
<button type='submit' className='btn' onClick={handleSubmit}>
add person
</button>
</form>
</article>
<article>
{people.map((person) => {
const { id, firstName, email, age } = person;
return (
<div key={id} className='item'>
<h4>{firstName}</h4>
<p>{email}</p>
<p>{age}</p>
</div>
);
})}
</article>
</>
);
};
export default ControlledInputs;
'Front-end > React' 카테고리의 다른 글
React - useReducer란? (0) | 2021.06.24 |
---|---|
useRef 란 ? (0) | 2021.06.23 |
React - removeEventListener (0) | 2021.06.18 |
React - useEffect : github user profile 만들기 (0) | 2021.06.18 |
useEffect 란? (0) | 2021.06.17 |