프로젝트 관련
React: react-router-dom:v6에서 경로 설정 및 PathVariable(경로 변수) 가져오기
khds
2023. 6. 10. 21:26
과거 프로젝트를 진행할 때 react-router-dom을 v5를 주로 사용했었다.
하지만 새로운 프로젝트에서 버전을 따로 등록하지 않고 설치 시 v6으로 설치되어 v5와 다른 부분들 때문에 시간을 뺐긴 경험이 있다.
간단하게 경로 설정, PathVarible(경로 변수)를 어떻게 가져오는지 비교해보자.
우선 v5에서다.
// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import Profile from './Profile';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/profile/:username" component={Profile} />
</Switch>
</Router>
);
}
export default App;
Switch를 사용했지만 v6에선 Switch가 없어 이를 그대로 사용한다면 에러메시지가 화면에 노출될 것이다.
v6에서는 아래와 같이 작성하자.
// App.js
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Home from "./Home";
import Profile from "./Profile";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile/:username" element={<Profile />} />
</Routes>
</Router>
);
}
export default App;
그렇다면 PathVariable는 어떻게 받을까?
이는 v5나 v6나 같으니 신경쓰지 않으면 된다.(함수형 컴포넌트)
// Profile.js
import React from "react";
import { useParams } from "react-router-dom";
function Profile() {
const { username } = useParams();
return (
<div>
<h1>Profile Page</h1>
<p>Username: {username}</p>
</div>
);
}
export default Profile;
끝.