<Link to>
valuesv5의 경우 경로가 /
로 시작하지 않는 <Link to>
의 값은 모호해지는 경우가 발생했다.
<Link to=”me”>
를 사용하는 경우
현재 URL이 /users
인 경우
→ <Link to=”me”>
== <a href=”/me”>
현재 URL이 /users/
인 경우
→ <Link to=”me”>
== <a href=”/users/me”>
이 문제는 Link가 어떻게 동작하는지 예측하는 걸 어렵게 했다.
이 때문에 상대적인 값이 Link를 사용해서 link를 구현하는 것 보다는 match.url과 같은 정보를 이용해서 link를 구현하기를 권장되었다.
<a href>
값을 가지도록 개선하였다..
, ..
도입현재 URL을 시스템의 디렉토리 경로인 것처럼 이해하고 상위 URL로 이동하고 싶을 경우 ..
을 이용할 수 있고 .
또한 사용할 수 있다.
// If your routes look like this
<Route path="app">
<Route path="dashboard">
<Route path="stats" />
</Route>
</Route>
// and the current URL is /app/dashboard (with or without
// a trailing slash)
<Link to="stats"> => <a href="/app/dashboard/stats">
<Link to="../stats"> => <a href="/app/stats">
<Link to="../../stats"> => <a href="/stats">
<Link to="../../../stats"> => <a href="/stats">
// On the command line, if the current directory is /app/dashboard
cd stats # pwd is /app/dashboard/stats
cd ../stats # pwd is /app/stats
cd ../../stats # pwd is /stats
cd ../../../stats # pwd is /stats
..
의 사용 시 주의 사항
<Route path=”:id/messages”>와 같이 Route path props가 여러가지 url 세그먼트를 가질 경우 <Link to=”..”>은 <a href=”..”>와 동일하지 않다.
이렇게 동작하는 것은 *를 이용하여 route 경로를 구성하는 경우에 효과적으로 사용할 수 있다.
function App() {
return (
<Routes>
<Route path=":userId">
<Route path="messages" element={<UserMessages />} />
<Route
path="files/*"
element={
// This links to /:userId/messages, no matter
// how many segments were matched by the *
<Link to="../messages" />
}
/>
</Route>
</Routes>
);
}
Link
component
propsimport { FancyPantsLink } from "@fancy-pants/design-system";
import {
useHref,
useLinkClickHandler,
} from "react-router-dom";
const Link = React.forwardRef(
(
{
onClick,
replace = false,
state,
target,
to,
...rest
},
ref
) => {
let href = useHref(to);
let handleClick = useLinkClickHandler(to, {
replace,
state,
target,
});
return (
<FancyPantsLink
{...rest}
href={href}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) {
handleClick(event);
}
}}
ref={ref}
target={target}
/>
);
}
);
<aside> 💡 v5의 <Link> component prop
v5에서는 Link component에 대해서 component prop을 제공한다. 이를 이용하면 Link나 NavLink Redirect(v5 기준)과 같은 navigation 기능을 하는 자신 만의 navigation component를 만들 수 있다.
여기서 navigation component란 React-Router에서 제공하는 컴포넌트 종류 중 한개이다.
const FancyLink = React.forwardRef(({ navigate, ...props }, ref) => {
return (
// a tag 이외에 다른 tag를 랜더링해도 된다.
<a ref={ref} {...props} onClick={handleClick}>💅 {props.children}</a>
)
})
<Link to="/" component={FancyLink} />
</aside>