React.js
react-router v6 달라진 점들
whoyoung90
2021. 12. 21. 13:33
반응형
1. Routes
- exact를 작성할 필요가 없어졌고, component 대신 element로 사용한다.
// 기존
<Route path={"/"} component={MainPage} exact />
<Route path={"/login"} component={OrderPage} exact />
// react-router v6
<Route path='/' element={<MainPage/>} />
<Route path='/order' element={<OrderPage/>} />
2. useNavigate()
- 동적라우팅 시, useHistory가 사라지고 useNavigate로 대체되었다.
// 기존
const history = useHistory();
history.push('/');
history.replace('/');
// react-router v6
const navigate = useNavigate();
navigate('/');
navigate('/', {replace: true});
3. useLocation()
- 현재 페이지 path 확인시, history객체가 아닌 useLocation을 활용한다.
// 기존
const history = useHistory();
console.log(history.location.pathname);
// react-router v6
const location = useLocation();
console.log(location.pathname);
4. scrollTo(0, 0)
- 페이지 상단으로의 스크롤
// 기존
document.getElementById('root').scrollTo(0, 0);
// react-router v6
document.documentElement.scrollTo(0, 0);
반응형