useNavigate()를 통해서 페이지를 이동할 때 useState로 담아 놓은 데이터를 이동하는 경로에 Props를 함께 전달하는 기능을 구현해 보려고 합니다.
First 컴포넌트에서는 사용자 이름을 input으로 받고 시작하기 버튼을 누르면 사용자의 이름이 이동한 페이지에 props가 잘 전달될 수 있도록 구현하는 것이 목표입니다.
useNavigate()
이동 경로로 state값 전달하기
const navigte() = useNavigate(); navigate("이동할 경로", state:{key:value});
import { useNavigate } from "react-router-dom";
import { useState } from "react";
import MyButton from "../components/MyButton";
const First = () => {
const navigate = useNavigate();
const [name, setName] = useState("");
return (
<div className="First">
<div class="wrap">
<div>
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<MyButton
onClick={() => {navigate("/home", {state:{key:{name}}})}}
/>
</div>
</div>
);
}
export default First;
useLocation()
이동한 경로에 state 값 가져오기
const location = useLocation(); const {name} = location.state.key;
const Home = () => {
const location = useLocation();
const {name} = location.state.key;
return(
<div className="Home">
<div className="wrap">
<section className="homeText">
안녕하세요. {name}님.
</section>
</div>
</div>
);
};