관리 메뉴

꿈꾸는 개발자

React Router useNavigate 살펴보기 본문

React Router

React Router useNavigate 살펴보기

rickysin 2023. 1. 25. 15:27

사용 목적: 

  • <Link />component를 사용하지 않고 페이지 이동을 할 때 사용하는 Hook이다
  const goBack = () => {
    // 이전 페이지로 이동
    // -2를 넣을 경우 뒤로 두 번 이동을 한다!
    navigate(-1);
  };

  const goArticles = () => {
    // articles 경로로 이동
    navigate('/articles');
  };
  • 이벤트 핸들러에 위 함수를 할당 할 경우 주석으로 처리된 기능으로 작동하게 된다!

사용법:

  • Hook의 첫 번째 인자로 이동하기 원하는 path를 주는 것(두 번째(replace) 인자의 경우 optional)  
const goArticles = () => {
  navigate('/articles', { replace: true });
}

 

  •  replace 옵션은 페이지 이동할 때 현재 페이지를 기록에 남기지 않는다 (default: false 기록을 남긴다는 의미!) History API에 기록이 남지 않기 때문에 뒤로 가기 버튼을 만들고 눌렀을 때 history stack에 있는 경로로 이동하게 된다 

 

  • 두 번째 인자로 객체를 전달하는 것은 state property를 전달할 수 있다는 뜻이다 
{
  state: { message: "Failed to submit form" },
  replace: false,
}

위와 같은 코드를 optional 인자로 전달했을 때 replace: false 이미 설명했듯이 기본값으로 history stack에 기록을 남기는 것을 의미한다. 

state:의 경우 <useLocation /> Hook을 통해 state의 값을 가져올 수 있다 => 유동적으로 data를 전달할 수 있다는 의미이다!

const location = useLocation();
console.log(location.state) 
// { message: 'Failed to submit form' }
  • 자연수 전달

첫 번째 goBack 함수의 예시처럼, 자연수를 전달하는 것은 history stack을 변경하는 것과 마찬가지이다. Navigate(-1)은 바루어저의 back button을 클릭한 것과 동일한 기능을 한다.


출처: 

https://velog.io/@velopert/react-router-v6-tutorial

 

React Router v6 튜토리얼

리액트 라우터 v6를 새로 접하시는 분들을 위한 튜토리얼을 작성했습니다. 리액트 라우터 v6 의 기본적인 사용법, 그리고 이 라이브러리에서 제공하는 다양한 유용한 기능들에 대해서 알아봅시

velog.io

https://refine.dev/blog/usenavigate-react-router-redirect/#how-to-use-the-usenavigate-hook

 

Redirect in React Router V6 with useNavigate hook | refine

We'll discover how to perform a redirect using useNavigate in React Router V6

refine.dev