import { useState } from 'react';
export function useFormInput(initialValue) {
const [value, setValue] = useState(initialValue);
function handleChange(e) {
setValue(e.target.value);
}
const inputProps = {
value: value,
onChange: handleChange
};
return inputProps;
}
useFormInput.jsimport { useFormInput } from './useFormInput.js';
export default function Form() {
const firstNameProps = useFormInput('Mary'); //{value: 'Marry', onChange:{..}} 형태
const lastNameProps = useFormInput('Poppins');
return (
<>
<label>
First name:
<input {...firstNameProps} /> // == <input value=".." onChange=".." />
</label>
<label>
Last name:
<input {...lastNameProps} />
</label>
<p><b>Good morning, {firstNameProps.value} {lastNameProps.value}.</b></p>
// input내의 값이 바뀌면 ~nameProps가 변경되어 리렌더링되고 이 부분도 변경됨
</>
);
}
App.js