❗️Error/오류를 해결하자!

[React] Link로 데이터 전달하는 방법

hellohailie 2023. 1. 9. 11:27

 

✔️ 해결하고자 하는 것

상태관리 툴까지 쓸 depth는 아니지만 부모와 자식 관계가 아닌 컴포넌트가 아니라 페이지일 때 데이터를 전달할 수 있으면 좋겠다고 생각함

 

 

 

✔️ 해결 방법

Link 과 Location 를 사용해서 문제를 해결할 수 있다. 

state로 {{}}를 두 번 묶어서 데이터를 전달할 수 있다. 

👇 데이터를 전달하는 컴포넌트 코드 👇

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

<Link
	to={`/todo/${id}`}
	state={{ id, title, content, createdAt, updatedAt }}
>
	<Title>{title}</Title>
</Link>

👇 데이터를 받는 페이지 코드 👇

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

const TodoDetail = () => {
  const location = useLocation();

  const title = location.state.title;
  const content = location.state.content;
  const createdAt = location.state.createdAt;
  const updatedAt = location.state.updatedAt;
  
  ...
  
  return (
  ...
     <div>{title}</div>
     <div>{content}</div>

 

 

😃 잘못된 개념 전달이 있다면 댓글 부탁드립니다. 저의 성장에 큰 도움이 됩니다🤓