ksw_devlog
TIL 02.03 본문
DOM 관련 타입스크립트 리팩토링
function TodoInsert({onSubmit}) {
const [content, setContent] = useState("");
const ref = useRef();
const handleChange = (e) => {
setContent(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
if (!content) return;
onSubmit(content);
setContent("");
};
useEffect(() => {
if (ref.current) {
ref.current.focus();
}
}, []);
return (
<Container>
<Form onSubmit={handleSubmit}>
<TextInput
ref={ref}
type={"text"}
placeholder="오늘 할 일"
value={content}
onChange={handleChange}
/>
<InputBtn
type="submit"
// onClick={handleSubmit}
>
작성
</InputBtn>
</Form>
</Container>
)
}
export default TodoInsert
=> Type script
function TodoInsert({onSubmit}: ToInsertprops) {
const [content, setContent] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setContent(e.target.value);
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!content) return;
onSubmit(content);
setContent("");
};
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return (
<Container>
<Form onSubmit={handleSubmit}>
<TextInput
ref={inputRef}
type={"text"}
placeholder="오늘 할 일"
value={content}
onChange={handleChange}
/>
<InputBtn
type="submit"
// onClick type 지정 ?
// onClick={handleSubmit}
>
작성
</InputBtn>
</Form>
</Container>
)
}
export default TodoInsert
form태그나 input태그에 맞춰서 알맞은 타입을 지정해주면 된다.