버튼을 클릭했을 때, 작성자와 일기가 정상적으로 입력되었는지 확인하고 아니라면 focus하기
DOM요소를 선택 조작을 도와주는 기능을 가지고 있다.
1. 설정
import {useRef,useState} from "react";
const authorInput = useRef();
const contentInput = useRef();
반환값을 상수에 담아 사용한다.
React.MutableRefObject
(Html에 접근하도록 한다.)가 저장된다. <div>
<input
ref = {authorInput}
name = "author"
value = {state.author}
onChange = {handleChange}
/>
</div>
ref = {authorInput}
을 작성해준다.
authorInput
으로 input요소에 접근할 수 있게 되었다.const handleSubmit = ()=>{
if(state.author.length <1){
authorInput.current.focus();
//useRef는 current메서드를 이용해 사용할 수 있다.
return;
}
if(state.content.length < 5){
contentInput.current.focus();
return;
}
alert("저장 성공!");
}
current
프로퍼티로 불러올 수 있다.입력된 값의 legnt에 조건이 맞지 않을 경우 focus기능을 이용하도록 useRef를 이용하였다.
import {useRef,useState} from "react";
const DiaryEditor = ()=>{
const authorInput = useRef();
const contentInput = useRef();
const [state , setState] = useState({
author : "",
content : "",
emotion : "1",
});
const handleChange = (e)=>{
setState({
...state,
[e.target.name] : e.target.value,
})
}
const handleSubmit = ()=>{
if(state.author.length <1){
//focus
authorInput.current.focus();
//useRef는 current메서드를 이용해 사용할 수 있다.
return;
}
if(state.content.length < 5){
contentInput.current.focus();
return;
}
alert("저장 성공!");
}
return(
<div className="DiaryEditor">
<h2>오늘의 일기</h2>
<div>
<input
ref = {authorInput}
name = "author"
value = {state.author}
onChange = {handleChange}
/>
</div>
<div>
<textarea
ref = {contentInput}
name = "content"
value = {state.content}
onChange = {handleChange}/>
</div>
<div>
<span>오늘의 감정점수 : </span>
<select
name = "emotion"
value = {state.emotion}
onChange = {handleChange}
>
<option vlaue ={1}>1</option>
<option vlaue ={2}>2</option>
<option vlaue ={3}>3</option>
<option vlaue ={4}>4</option>
<option vlaue ={5}>5</option>
</select>
</div>
<div>
<button onClick={handleSubmit}>일기 저장하기</button>
</div>
</div>
)
}
export default DiaryEditor;