http://localhost:3000/sub/ <- 이런 식으로 마지막에 "/"가 붙는 거 때문에 곤란해서 삭제할 방법을 찾았었다.
StackOverFlow에 있는 코드를 참고해서 작성했다.
1. Util Component
import React from "react";
import { Navigate, useLocation } from "react-router-dom";
const RemoveEndUrlSlash = ({ ...rest }) => {
const location = useLocation();
// If the last character of the url is '/'
if (location.pathname.match("/.*/$")) {
return (
<Navigate
replace
{...rest}
to={{
pathname: location.pathname.replace(/\/+$/, ""),
search: location.search,
}}
/>
);
} else return null;
};
export default RemoveEndUrlSlash;
2. app 컴포넌트 내부에 합성
import React, { useEffect } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import AppLayout from "./components/AppLayout";
import RemoveEndUrlSlash from "./Util/RemoveEndUrlSlash";
const App = () => {
const { pathname } = useLocation();
const navigate = useNavigate();
useEffect(() => {
if (pathname !== "/") {
return;
} else {
navigate("/reservation-list/list", { replace: true });
console.log("moved root to reservation List");
}
}, [pathname]);
return (
<>
<RemoveEndUrlSlash /> // Here!
<AppLayout>
<Outlet />
</AppLayout>
</>
);
};
export default App;
참고
How to remove trailing slash in react-router URLs
I start to use react-router in my application and I am noting that when it has a trailing slash at end of URL (/url/) it does not work. I searched more about it, read all documentation and react-ro...
stackoverflow.com
'React & Library > Router' 카테고리의 다른 글
[React / Router] Link 에서 state로 값 넘기기 (0) | 2022.12.16 |
---|---|
[React / Router] v6 - creatBrowserRouter basename (baseURL) 설정 방법 (0) | 2022.12.13 |
[React / Router] React Router V6 Guide (Basic) - 부제 : v6 변경점 (1) | 2022.12.05 |
[React Router] 특정 경로 접속 시, 다른 경로로 변경 (리다이렉트) 하기 (0) | 2021.08.02 |
댓글