code-share/renderer/link.tsx

33 lines
724 B
TypeScript
Raw Normal View History

2024-02-23 19:36:10 +07:00
import React from "react";
2024-02-22 12:14:58 +00:00
import { usePageContext } from "./context";
2024-02-23 19:36:10 +07:00
import { Slot } from "@radix-ui/react-slot";
2024-02-22 12:14:58 +00:00
2024-02-23 19:36:10 +07:00
type LinkProps = {
href?: string;
className?: string;
asChild?: boolean;
children?: React.ReactNode;
};
const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
({ asChild, href, ...props }, ref) => {
const pageContext = usePageContext();
const { urlPathname } = pageContext;
const Comp = asChild ? Slot : "a";
2024-02-22 12:14:58 +00:00
const isActive =
href === "/" ? urlPathname === href : urlPathname.startsWith(href!);
2024-02-22 12:14:58 +00:00
return (
<Comp
ref={ref}
data-active={isActive || undefined}
href={href}
{...props}
/>
);
}
);
2024-02-22 12:14:58 +00:00
export default Link;