const authorInput = useRef();
...
const handleSubmit = ()=>{
if(state.author.length<1){
authorInput.current.focus();//현재 가리키는 요소를 current로 불러와서 사용
return;
}
if(state.author.length<5){
alert("일기 본문은 최소 5글자 이상 입력해주세요");
return;
}
alert('저장 성공!');
}
...
<input
ref={authorInput}
name='author'
value={state.author}
onChange={handleChangeState}
/>
const authorInput: React.MutableRefObject
이와같이 React.MutableRefObject가 저장된다. 이건 Dom요소를 접근할 수 있는 기능을 한다.
localContentInput = useRef변수 선언
const localContentInput = useRef();
//선택할 요소 (textarea)에 ref달기
<textarea
ref={localContentInput}
value={localContent}
onChange={(e) => setLocalContent(e.target.value)}
/>
//요소 사용
const handleEdit = () => {
if (localContent.length < 5) {
localContentInput.current.focus();
return;
}
onEdit(id, localContent);
};
컴포넌트 안에서 조회 및 수정 할 수 있는 변수를 관리
**useRef 로 관리하는 변수는 값이 바뀌어도 컴포넌트 리렌더링 되지 않는다.
이 값을 수정 할때에는 .current 값을 수정, 조회 할 때에는 .current 를 조회한다.
다음과 같이 defaultProps를 지정해 줄 수 있다.
const DiaryList = ({ diaryList }) => {
console.log(diaryList);
return (
<div className="DiaryList">
<h2>일기 리스트</h2>
<h4>{diaryList.length}개의 일기가 있습니다.</h4>
<div>
{diaryList.map((it) => (
<div>
<div>작성자 : {it.author}</div>
<div>일기 : {it.author}</div>
<div>작성 시간(ms) : {it.created_date}</div>
</div>
))}
</div>
</div>
);
};
DiaryList.defaultProps = {
diaryList: [],
};