react

[240526 TIL] Link state

adminisme 2024. 5. 26. 08:05

오늘은 React Router를 이용해 Link 컴포넌트를 통해 라우트 이동시 Props를 전송할 수 있는지가 궁금했습니다.
공부해보니 역시 가능했고, 이를 위해 state 속성을 사용할 수 있습니다.

 

React Router 의 Link 컴포넌트는 state 속성을 통해 데이터를 전달할 수 있으며,
전달된 데이터는 도착한 컴포넌트에서 useLocation 훅을 통해 접근할 수 있습니다.

 

코드 예시

  1. 데이터를 전달하는 Link 설정:
 // List.js
import { Link } from "react-router-dom";
import styled from "styled-components";
import { Expend } from "../../types/d";
import Card from "../Card";

const StyledSection = styled.section`
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 0.6rem;
    width: 100%;
    padding: 1rem 0;
    height: auto;
    background-color: white;
    border-radius: 5px;
`;

const StyledLink = styled(Link)`
    width: 100%;
`;

type ListProps = {
    monthlyExpends: Expend[];
    deleteExpend: (arg: string) => void;
    updateExpend: (arg: Expend) => void;
};

function List({ monthlyExpends }: ListProps) {
    return (
        <StyledSection>
            {monthlyExpends.map((expend) => (
                <StyledLink
                    key={expend.id}
                    to={`/detail/${expend.id}`}
                    state={{ expend }}
                >
                    <Card expend={expend} />
                </StyledLink>
            ))}
        </StyledSection>
    );
}

export default List;

 

  1. 전달된 데이터를 받는 컴포넌트:
// Detail.js
import { useLocation } from "react-router-dom";
import { Expend } from "../../types/d";

function Detail() {
    const location = useLocation();
    const { expend } = location.state as { expend: Expend };

    return (
        <div>
            <h1>Detail Page</h1>
            <p>ID: {expend.id}</p>
            <p>Amount: {expend.amount}</p>
            <p>Description: {expend.description}</p>
        </div>
    );
}

export default Detail;

설명

  1. List 컴포넌트:
    • Link 컴포넌트에 state 속성을 추가하고, 이 속성에 전달할 데이터를 설정합니다.
    • 예를 들어, state={{ expend }}expend 객체를 state로 전달합니다.
  2. Detail 컴포넌트:
    • useLocation 훅을 사용하여 현재 위치 객체를 가져옵니다.
    • location.state를 통해 전달된 데이터를 접근할 수 있습니다.
    • location.stateLink에서 전달된 state 객체를 포함합니다. 타입스크립트를 사용하여 타입을 명시적으로 지정할 수 있습니다.

이 방법을 사용하면 Link 컴포넌트를 통해 라우트 이동 시 데이터를 전달할 수 있으며, 도착한 컴포넌트에서 이를 받아 사용할 수 있습니다.