Integration with TanStack Router #2666
-
I'm setting up a new project that uses NextUI and TanStack Router and I'm trying to figure out how to integrate the two such that I can create NextUI-styled links and button links that are able to leverage the type safety and prefetching of TanStack Router Links. I feel like most of the pieces are available to me with the useLink hook and TanStack's interfaces (see this discussion) but I'm struggling to figure out how to put everything together. Has anyone done this or have an idea as how to do so? Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I've got something I think works, but I'd love feedback, especially since overriding import { LinkProps, useLink } from "@nextui-org/react";
import { forwardRef } from "react";
import { linkAnchorClasses } from "@nextui-org/theme";
import { LinkIcon } from "@nextui-org/shared-icons";
import { LinkOptions } from "@tanstack/react-router";
import { Link as TsrLink } from "@tanstack/react-router";
type Props = LinkOptions & Omit<LinkProps, "as">;
export const Link = forwardRef<HTMLAnchorElement, Props>((props, ref) => {
const {
Component,
children,
showAnchorIcon,
anchorIcon = <LinkIcon className={linkAnchorClasses} />,
getLinkProps,
} = useLink({
as: TsrLink,
...props,
ref,
});
return (
<Component {...getLinkProps()}>
<>
{children}
{showAnchorIcon && anchorIcon}
</>
</Component>
);
});
Link.displayName = "Link"; |
Beta Was this translation helpful? Give feedback.
-
I happened to make it work with react-aria-components, but it could easily converted to NextUI. import { useLocation } from "@tanstack/react-router";
import { Link, LinkProps } from "react-aria-components";
function _Link({ href, children, style, className, ...props }: LinkProps) {
const location = useLocation();
const isCurrent = location.pathname === href;
return (
<Link
href={href}
{...(isCurrent && { "aria-current": true })}
className={({
isHovered,
isPressed,
isFocused,
isFocusVisible,
isDisabled,
defaultClassName,
}) => {
const ret =
typeof className === "function"
? className({
isCurrent,
isHovered,
isPressed,
isFocused,
isFocusVisible,
isDisabled,
defaultClassName,
})
: className;
return ret || "";
}}
{...props}
style={({
isHovered,
isPressed,
isFocused,
isFocusVisible,
isDisabled,
defaultStyle,
}) => {
const ret =
typeof style === "function"
? style({
isCurrent,
isHovered,
isPressed,
isFocused,
isFocusVisible,
isDisabled,
defaultStyle,
})
: style;
return ret || {};
}}
>
{({
isHovered,
isPressed,
isFocused,
isFocusVisible,
isDisabled,
defaultChildren,
}) => {
const ret =
typeof children === "function"
? children({
isCurrent,
isHovered,
isPressed,
isFocused,
isFocusVisible,
isDisabled,
defaultChildren,
})
: children;
return <>{ret}</>;
}}
</Link>
);
}
export { _Link as Link }; |
Beta Was this translation helpful? Give feedback.
See this https://nextui.org/docs/guide/routing#tanstack