[React] useNavigate로 state 넘기기

HUYKSKEE·2022년 8월 20일
3

리액트에서 화면이동을 위해서는 두가지 방법이 있다.
LinkuseNavigate가 있는데 오늘은 useNavigate를 이용해 스테이트를 넘기는 걸 해보려한다.

1. 라이브러리 설치

npm install react-router-dom --save

2. useNavigate 인자

navigate("/이동할주소",{replace:true});

  • 첫 번째 인자로 내가 이동할 주소를 받고 두 번째 인자로 {replace, state}인수를 사용한다.

replace (true or false)

-true를 쓰면 이동할 주소로 이동한후 뒤로가기가 안된다. 뒤로가기를 누르면 메인페이지("/")로 돌아가게된다.

  • false를 누르면 뒤로가기가 가능한데 이게 기본값이다.

state 넘겨주기

import { useNavigate } from "react-router-dom";

function Card({ list }) {
 
  const navigate = useNavigate(); // 

  return (
    <div>
      {list.map(list => {
        return (
          <div key={list.id}>
            <img
              src={list.image}
              alt=""
              width="300px"
              height="300px"
              onClick={() =>
                navigate('/DetailPage', {
                  // props로 받는 list 스테이트를 넘겨준다.
                  state: { ...list },
                })
              }
            />
            {list.type}
          </div>
        );
      })}
    </div>
  );
}

3. useLocation

  • 전달받은 state는 useLocation()훅을 이용해 취득할 수 있다.

예제코드

import OverView from './OverView/OverView';
import { useLocation } from 'react-router-dom';
function DetailPage() {  
// state 취득
  const location = useLocation(); 
// location.state로 접근해서 필요한 데이터 사용
  console.log(location.state);
  return (
    <div>
      <h1>header</h1>
      <OverView />
    </div>
  );
}
  • 결과
profile
개가수(개발자 + 가수) 🙏개발자들의 공유 문화를 지향합니다.🤝

1개의 댓글

comment-user-thumbnail
약 23시간 전

Really useful walkthrough of how use Navigate works for passing state in React — your examples are clear and easy to follow. I especially liked how you showed the difference between pushing state and navigating directly.

If you're experimenting with other tools to help with web development or managing state and routing, you might want to check out https://instaupp.org
— it's not directly tied to React, but sometimes trying out cross-domain tools can spark new workflow ideas. Thanks for sharing this!

답글 달기