- 페이지를 이동시키면서 state를 전달하는 방법에 대해서 알아보았다.
- react-router-dom v5를 사용하였다.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import App from "./App";
import NextPage from "./NextPage";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<BrowserRouter>
<Switch>
<Route exact path="/">
<App />
</Route>
<Route path="/next">
<NextPage />
</Route>
</Switch>
</BrowserRouter>
</StrictMode>
);
App.js
텍스트를 입력 후, 버튼을 누르면 text 값에 입력값을 넣어 다음 페이지에 전달한다.
import { useState } from "react";
import "./styles.css";
import { useHistory } from "react-router-dom";
export default function App() {
const [text, setText] = useState("");
const history = useHistory();
return (
<div className="App">
<input
type="text"
placeholder="input"
onChange={(e) => {
setText(e.target.value);
}}
/>
<button
onClick={() =>
history.push({
pathname: "/next",
state: { text }
})
}
>
이동하기
</button>
</div>
);
}
NextPage.js
전달받은 값을 확인할 수 있다.
import { useLocation } from "react-router-dom";
const NextPage = () => {
const location = useLocation();
console.log(location);
return (
<div>
<p>Text : {location.state.text}</p>
</div>
);
};
export default NextPage;
- react-router-dom v6에서는 메서드의 변경으로 useHistory가 아닌 useNavigate를 사용한다.
- 또한, 라우팅을 설정하는 부분 역시 변경되었다.
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import App from "./App";
import NextPage from "./NextPage";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="/next" element={<NextPage />} />
</Routes>
</BrowserRouter>
</StrictMode>
);
import { useState } from "react";
import "./styles.css";
import { useNavigate } from "react-router-dom";
export default function App() {
const [text, setText] = useState("");
const navigate = useNavigate();
return (
<div className="App">
<input
type="text"
placeholder="input"
onChange={(e) => {
setText(e.target.value);
}}
/>
<button
onClick={() =>
navigate("/next", {
state: { text }
})
}
>
이동하기
</button>
</div>
);
}
react router dom 공식문서 : https://reactrouter.com/en/main