728x90
1. switch 대신 Routes 사용
- Switch 의 네이밍이 Routes로 변경되었습니다 :)
- exact 옵션 삭제
- component 대신 element 사용
- path 를 기존의 path="/Web/:id" 에서 path=":id" 로, 상대경로로 지정
- 이 외에도, path="." / path=".." 등으로 상대경로를 표현한다
기존 방식 (v5)
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./pages/Home";
import Write from "./pages/Write";
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/" component={() => <Home />} />
<Route exact path="/write" component={() => <Write />} />
<Route component={() => <div>Page Not Found</div>} />
</Switch>
</BrowserRouter>
);
}
export default App;
변경된 방식 (v6)
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { Main, Page1, Page2, NotFound } from "../pages";
import { Header } from ".";
const Router = () => {
return (
<BrowserRouter>
<Header />
<Routes>
<Route path="/" element={<Main />} />
<Route path="/page1/*" element={<Page1 />} />
<Route path="/page2/*" element={<Page2 />} />
<Route path="/*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
};
export default Router;
2. URL Params 읽는 법
- match 객체 아닌 useParams 사용으로 변경
기존 방식 (v5)
const Profile = ({ match }) => {
// v5에선 파라미터를 받아올 땐 match 안에 들어있는 params 값을 참조
const { username } = match.params;
}
<Route path="/profiles/:username" component={Profile} />
변경된 방식 (v6)
import { useParams } from 'react-router-dom';
const Profile = () => {
const { username } = useParams();
}
<Route path="/profiles/:username" element={<Profile />} />
3. history, useHistory 대신 useNavigate로 교체
- v5에서는 라우트로 사용된 컴포넌트에게 match, location, history 객체가 props로 전달되었음.
- v6에서는 useHistory 가 아예 사라지고 history도 기존 선언방식으로 선언하면 안됨. 기존 history의 모든 기능은 useNavigate로 통합됨
기존 방식 (v5)
function HistorySample({ history }) {
// 뒤로가기
const goBack = () => {
history.goBack();
};
// 홈으로 이동
const goHome = () => {
history.push('/');
}
return ( ... );
}
변경된 방식 (v6)
// history를 쓰고싶은 경우
import { createBrowserHistory} from 'react-router-dom';
const history = createBrowserHistory();
// useNavigate 사용하는법
import { useNavigate } from 'react-router-dom';
function NavigateSample() {
const navigate = useNavigate();
// 뒤로가기
// 인덱스로 처리, 두번 뒤로 가고싶으면 -2
const goBack = () => {
navigate(-1);
}
// 홈으로 가기
const goHome = () => {
navigate('/');
}
return ( ... );
}
출처:
https://intrepidgeeks.com/tutorial/react-changes-after-upgrading-to-router-v6
728x90
'React' 카테고리의 다른 글
[React]react hook & SpringBoot [2/2] (0) | 2022.08.07 |
---|---|
[React]react hook & SpringBoot [1/2] (0) | 2022.03.23 |
댓글