배워서 남 주자

react-router-dom의 <Link>로 이미 가지고 있는 데이터 넘겨주기

미래에서 온 개발자 2023. 8. 22. 09:43

<Link>를 사용하는 가장 흔한 패턴은 다음과 같이 to 속성으로 경로를 지정해주는 것이다.

        <Link to="/signin">로그인</Link>
        <Link to="/signup">회원가입</Link>

 
이제 다음과 같은 경우를 생각해보자. 상품 목록 페이지가 있고, 상품 카드를 클릭하면 상품 상세 페이지로 넘어간다. 상품 목록 페이지에서 상세 페이지로 넘어갈 때 보통 router에서 /:productId와 같은 형태로 url parameter로 상품의 ID를 넘기고, 상세 페이지에서는 const { productId } = useParams(); 로 product ID를 받아 상품 상세 정보를 다시 fetch한다. 
 

        <productList>
          {products?.map((product) => (
            <Product key={product.id}>
              <Link to={`/${product.id}`}>
                {product.name} &rarr;
              </Link>
            </Product>
          ))}
        </ProductList>

 
상품 상세페이지의 소제목이나 브라우저의 탭의 <title> 정보를 상품명을 렌더링하고 싶다면 productId로 다시 fetch를 받은 데이터로 보여줄 수 있다. 하지만 productList에서 우리는 이미 상품의 id와 name을 가지고 있다. 이 정보를 상세 페이지로 바로 넘겨준다면 fetch를 요청하면서 loading 중일 때도 상품명을 사용자에게 보여줄 수 있고, 이로써 더 나은 사용자 경험을 제공할 수 있다. 
 
이때 <Link>의 속성 중 state를 사용하면 상세페이지로 데이터를 넘겨줄 수 있다. 
 

// ProductList.tsx
<Link to={`/${product.id}`} state={{ name: product.name }}>
    {product.name} &rarr;
</Link>
// Product.tsx
function Product() {
  const { state } = useLocation();
  
  // some fetch logic

  return (
      <Header>
        <Title>
          {state?.name ? state.name : isLoading ? 'Loading...' : data?.name}
        </Title>
      </Header>
  );
}

 
📚 참고자료

Link v6.15.0

This is the web version of . For the React Native version, go here. Type declarationdeclare function Link(props: LinkProps): React.ReactElement; interface LinkProps extends Omit< React.AnchorHTMLAttributes , "href" > { replace?: boolean; state?: any; to: T

reactrouter.com