[React] Router (version 6)
2023. 10. 2. 18:18ㆍReact
728x90
반응형
1. Installation
npm install react-router-dom@6
2. Setting
1) src/index.js
<BrowserRouter>
로 App을 감싼다.
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
2) src/App.js
<Routes>
안에서 필요한 페이지들을 <Route>
태그를 이용해 정의해둔다.
path 속성에 담은 값이 각 페이지의 경로가 된다.
import "./App.css";
import { Routes, Route } from "react-router-dom";
import Homepage from "./page/Homepage";
import Aboutpage from "./page/Aboutpage";
function App() {
return (
<div>
<Routes>
{/* 각 페이지를 정의한다. */}
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/product" element={<Product />} />
</Routes>
</div>
);
}
export default App;
3. Routing
페이지를 이동하는 방법은 두 가지가 있다.
1) <Link>
<Link>
태그 이용하기
import React from "react";
import { Link } from "react-router-dom";
const Home = () => {
return (
<div>
<h1>Home</h1>
<Link to="/about">About</Link>
</div>
);
};
export default Home;
2) useNavigate()
useNavigate()
hook 이용하기
import React from "react";
import { useNavigate } from "react-router-dom";
const About = () => {
const navigate = useNavigate();
const goToHomepage = () => {
navigate("/");
};
return (
<div>
<h1>About</h1>
<button onClick={goToHomepage}>Go to Homepage</button>
</div>
);
};
export default About;
4. Parameter :: useParams()
path를 작성할 때 :id
형태로 작성하면 매개변수가 된다.
function App() {
return (
<div>
<Routes>
<Route path="/product/:id/:num" element={<ProductDetail />} />
</Routes>
</div>
);
}
매개변수 읽어오기
import React from "react";
import { useParams } from "react-router-dom";
const ProductDetail = () => {
const params = useParams();
console.log(params);
~~~ 생략 ~~~
};
export default ProductDetail;
5. Query String :: useSearchParams()
q=pants
라는 쿼리 스트링을 붙여서 product 페이지로 이동한다고 했을 때,
navigate("/product?q=pants");
product 페이지에서 쿼리를 읽는 방법
import React from "react";
import { useSearchParams } from "react-router-dom";
const Product = () => {
let [query, setQuery] = useSearchParams();
console.log(query.get("q"));
~~~ 생략 ~~~
};
export default Product;
6. Redirect :: <Navigate>
조건에 따라 페이지 분기하는 방법
import { Routes, Route, Navigate } from "react-router-dom";
import { useState } from "react";
import Login from "./page/Login";
import User from "./page/User";
function App() {
const [authenticate, setAuthenticate] = useState(false);
const PrivateRoute = () => {
return authenticate ? <User /> : <Navigate to="/login" />;
};
return (
<div>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/user" element={<PrivateRoute />} />
</Routes>
</div>
);
}
export default App;
728x90
반응형
'React' 카테고리의 다른 글
[Redux] Redux, React Redux, Redux DevTools (1) | 2023.10.03 |
---|---|
[React] Class Component (0) | 2023.10.02 |
[React] Describing the UI (2) | 2023.09.27 |