Link Options
Link
, redirect
, 또는 navigate
에 전달할 옵션을 재사용하고 싶을 때, 객체 리터럴로 Link
에 전달할 옵션을 표현하는 것이 좋을 수 있습니다.
const dashboardLinkOptions = {
to: "/dashboard",
search: { search: "" },
};
function DashboardComponent() {
return <Link {...dashboardLinkOptions} />;
}
여기에는 몇 가지 문제가 있습니다. dashboardLinkOptions.to
는 string
으로 추론되며, 기본적으로 이는 Link
, navigate
또는 redirect
에 전달될 때 모든 경로에 대해 해결됩니다(as const
를 사용하여 이 특정 문제를 해결할 수 있음). 또 다른 문제는 dashboardLinkOptions
가 Link
로 확장될 때까지 타입 검사기를 통과하는지 알 수 없다는 점입니다. 잘못된 탐색 옵션을 쉽게 생성할 수 있으며, 이러한 옵션이 Link
에 확장될 때만 타입 오류가 있다는 것을 알 수 있습니다.
Using linkOptions
function to create re-usable options
linkOptions
는 객체 리터럴을 타입 검사하고 추론된 입력을 그대로 반환하는 함수입니다. 이는 사용되기 전에 Link
와 동일한 방식으로 옵션에 대해 타입 안전성을 제공하며, 유지보수성과 재사용성을 높여줍니다. 위의 예제를 linkOptions
를 사용하여 다음과 같이 작성할 수 있습니다:
const dashboardLinkOptions = linkOptions({
to: "/dashboard",
search: { search: "" },
});
function DashboardComponent() {
return <Link {...dashboardLinkOptions} />;
}
이 방법은 dashboardLinkOptions
에 대한 즉각적인 타입 검사를 허용하며, 이후 어디에서나 재사용할 수 있습니다.
const dashboardLinkOptions = linkOptions({
to: "/dashboard",
search: { search: "" },
});
export const Route = createFileRoute("/dashboard")({
component: DashboardComponent,
validateSearch: (input) => ({ search: input.search }),
beforeLoad: () => {
// redirect에 사용할 수 있음
throw redirect(dashboardLinkOptions);
},
});
function DashboardComponent() {
const navigate = useNavigate();
return (
<div>
{/** navigate에 사용할 수 있음 */}
<button onClick={() => navigate(dashboardLinkOptions)} />
{/** Link에 사용할 수 있음 */}
<Link {...dashboardLinkOptions} />
</div>
);
}
An array of linkOptions
탐색을 생성할 때 배열을 반복하여 탐색 바를 구성할 수 있습니다. 이 경우, linkOptions
를 여러 번 호출하여 배열을 생성하고 이를 사용하여 Link
배열을 렌더링할 수 있습니다.
const options = [
linkOptions({
to: "/dashboard",
label: "Summary",
activeOptions: { exact: true },
}),
linkOptions({
to: "/dashboard/invoices",
label: "Invoices",
}),
linkOptions({
to: "/dashboard/users",
label: "Users",
}),
];
function DashboardComponent() {
return (
<>
<div className="flex items-center border-b">
<h2 className="text-xl p-2">Dashboard</h2>
</div>
<div className="flex flex-wrap divide-x">
{options.map((option) => {
return (
<Link
{...option}
key={option.to}
activeProps={{ className: `font-bold` }}
className="p-2"
>
{option.label}
</Link>
);
})}
</div>
<hr />
<Outlet />
</>
);
}
linkOptions
의 입력은 추론되고 반환됩니다. label
의 사용 예에서 알 수 있듯이, 이는 Link
props에 존재하지 않는 속성입니다.