22.05.14
JS를 사용하면서 getElementById
, querySelector
등으로 특정DOM을 선택해왔다.
리액트에선 ref를 통해 사용한다.
아래 useNavigate ex)에서 설명
useNavigate는 양식제출, 특정 상황 이후 url을 조작하는 기능이다.
ex)
export default function Writing() {
const contentRef = useRef(null);
const titleRef = useRef(null);
const navigate = useNavigate();
function storySubmit(e) {
e.preventDefault();
fetch('https://elice-server.herokuapp.com/board', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
nickname: '내이름', // 사용자 닉네임 받아와야함
title: titleRef.current.value,
content: contentRef.current.value,
id: 'id3@gmail.com', // 사용자 id 받아와야 함
}),
})
.then((res) => res.json())
.then((data) => {
console.log(data);
navigate(`/Read/${data.data.post_idx}`);
});
}
...
<input type="text" placeholder="제목을 입력하세요" ref={titleRef} />
fetch 로 POST이후 생성되는 data.post_idx값을 이용해
navigate(`/Read/${data.data.post_idx}`);
의 주소로 이동한다.
아래 한줄 코드도 같은 동작을 한다.
window.location.href = `Read/${data.data.post_idx}`;
useRef()를 이용해 ref객체를 생성 -> 선택하고 싶은 DOM에 ref값으로 설정한다.
해당 객체의 .current값은 내가 정한 DOM을 가져오게 된다.
위 코드의 경우 titleRef.current.value 으로 input의 value 값을 가져와 POST한다.