이번에 사용할 것은 useRef인데요! 지난번에 만들던 프로젝트를 연결해서 만들어보겠습니다.
import {useRef} from "react" react로부터 useRef를 import해옵니다.
import { useRef } from "react";
1. DiaryEditor Component안에 const authorInput=useRef, const contentInput=useRef로 useRef객체를 만들어줍니다.
2. state.author.length<1조건을 만족하면 authorInput.current.focus()로, 현재 가리키는 값(current)에 focus시켜줍니다.
3. focus시킬 input요소의 속성에 ref = {authorInput}을 추가시켜줍니다.
const DiaryEditor = () => {
const authorInput = useRef(); // DOM요소에 접근할 수 있는 Reference
const contentInput = useRef();
});
const handleSubmit = () => {
if (state.author.length < 1) {
authorInput.current.focus();
return;
}
alert("저장 성공");
};
return (
<div className="DiaryEditor">
<h2>오늘의 일기</h2>
<div>
<input
ref={authorInput}
name="author"
value={state.author}
onChange={handleChangeState}
/>
</div>
</div>
)
이제, state.author.length<1조건을 만족한 상태로 handleSubmit(제출 버튼)이 실행되면 authorInput.current.focus()될 것입니다.
'WebProgramming > React' 카테고리의 다른 글
[React] Hook (0) | 2022.07.07 |
---|---|
[React] 부모 Component -> 자식 Component에게 함수/리스 전달하기 (0) | 2022.07.04 |
[React] 자식 Component -> 부모 Component로 데이터 전달하기 (0) | 2022.07.04 |
[React] List Rendering (0) | 2022.07.03 |
[React] React 프로젝트 - DiaryEditor Component (0) | 2022.07.01 |
[React] Props (0) | 2022.07.01 |
[React] useState를 이요한 상태 관리 (0) | 2022.07.01 |
[React] Promise와 Async&Await (0) | 2022.06.30 |