[React / Router] Link 에서 state로 값 넘기기
전달하는 Link
<Link to={`/${coin.id}`} state={coin.name}> // state로 주면 된다.
<Img src={`https://coinicons-api.vercel.app/api/icon/${coin.symbol.toLocaleLowerCase()}`} />
<Text>{coin.name} →</Text>
</Link>
이렇게 하면 state에 값이 넘어간다. react router v6 에서 좀 더 간편해졌다. 예전에는 to 에 객체를 통째로 넣어야 했는데.. 지금은 state에 넣을 수 있게 되었다. state={{ name=coin.name }} 이런 식으로 작성도 가능해졌다.
전달받은 Link의 컴포넌트
전달받은 Link에 해당하는 Component에서는 useLocation 을 사용하도록 한다.
useLocation().state를 받기 위해서 const { state } 라고 선언해주어서 사용하면 된다.
import { useLocation } from "react-router-dom";
const Coin = (props: any) => {
const { state } = useLocation();
console.log("state ", state);
};
참고
Link v6.4.5
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
declare function Link(props: LinkProps): React.ReactElement;
interface LinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
"href"
> {
replace?: boolean;
state?: any;
to: To;
reloadDocument?: boolean;
}
type To = string | Partial<Path>;
https://intrepidgeeks.com/tutorial/forwarding-status-via-responselink-router-v6
[React] Link를 통해 State 전달하기 ( Router v6 )
1. 기존의 방식 기존의 방식대로 Link를 통해 State를 전달하려는데.. Test 해당 방식대로 state를 전달해도 빈 객체만 보이는 현상을 발견했다. 찾아보니 react-router 버전이 업그레이드 되면서 더이상
intrepidgeeks.com