프론트엔드

react-router-dom 으로 첫번째 페이지 라우팅하기

yoxxin 2024. 1. 1. 03:07

1. 문제상황

vite + react 기반의 프로젝트에서 실행 시 첫번째 페이지를 /products 로 리다이렉트 하고싶었다.

App 컴포넌트는 뼈대인 Header 컴포넌트를 가지고 있고, Outlet을 이용해 나머지 페이지들을 렌더링한다.

처음에는 react router dom에서 제공하는 useNavigate 훅을 이용해서 구현했으나 useEffect가 거슬린다.

코드 자체가 명령적이고 App 내부에 숨겨져 있어 기능을 추적하기 까다롭다.

Effect에서 routing을 한다.

2. 해결방법

react router dom에서 제공하는 Navigate 컴포넌트가 있다.

A <Navigate> element changes the current location when it is rendered. It's a component wrapper around 
useNavigate, and accepts all the same arguments as props.

 

렌더링 할때 현재 위치를 이동시키고, useNavigate 래퍼 컴포넌트이다.

Router 컴포넌트에서 App 컴포넌트에 나란하게 Navigate를 선언하여 코드를 선언적으로 작성할 수 있는 장점이 있다.

 

참고로 "replace" prop의 의미는 다음과 같다. 

(교차검증했음)

3. 추가 정보

https://gist.github.com/mjackson/b5748add2795ce7448a366ae8f8ae3bb

 

Notes on handling redirects in React Router v6, including a detailed explanation of how this improves on what we used to do in v

Notes on handling redirects in React Router v6, including a detailed explanation of how this improves on what we used to do in v4/5 - redirects-in-react-router-v6.md

gist.github.com

react router dom v6 에서의 전반적인 redirect 방법에 관한 gist글이 있어서 첨부한다.