While repeating yourself can be acceptable in many situations, you might find that you do it too often. At times, you may want to create cross-cutting components with additional behavior or styles. You might also consider using third-party libraries in combination with TanStack Router's type safety.
If you want to create a basic custom link component, you can do so with the following:
import * as React from 'react'
import { createLink, LinkComponent } from '@tanstack/react-router'
interface BasicLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
// Add any additional props you want to pass to the anchor element
}
const BasicLinkComponent = React.forwardRef<HTMLAnchorElement, BasicLinkProps>(
(props, ref) => {
return (
<a ref={ref} {...props} className={'block px-3 py-2 text-blue-700'} />
)
},
)
const CreatedLinkComponent = createLink(BasicLinkComponent)
export const CustomLink: LinkComponent<typeof BasicLinkComponent> = (props) => {
return <CreatedLinkComponent preload={'intent'} {...props} />
}
React Aria Components example
React Aria Components v1.11.0 and later works with TanStack Router's preload (intent) prop. Use createLink to wrap each React Aria component that you use as a link.
Loading...
To use React Aria's render props, including the className, style, and children functions, create a wrapper component and pass that to createLink.
Chakra UI example
import * as React from 'react'
import { createLink, LinkComponent } from '@tanstack/react-router'
import { Link } from '@chakra-ui/react'
interface ChakraLinkProps extends Omit<
React.ComponentPropsWithoutRef<typeof Link>,
'href'
> {
// Add any additional props you want to pass to the link
}
const ChakraLinkComponent = React.forwardRef<
HTMLAnchorElement,
ChakraLinkProps
>((props, ref) => {
return <Link ref={ref} {...props} />
})
const CreatedLinkComponent = createLink(ChakraLinkComponent)
export const CustomLink: LinkComponent<typeof ChakraLinkComponent> = (
props,
) => {
return (
<CreatedLinkComponent
textDecoration={'underline'}
_hover={{ textDecoration: 'none' }}
_focus={{ textDecoration: 'none' }}
preload={'intent'}
{...props}
/>
)
}
MUI example
There is an example available which uses these patterns.
Link
If the MUI Link should simply behave like the router Link, it can be just wrapped with createLink:
Loading...
If the Link should be customized this approach can be used:
Loading...
If a Button should be used as a router Link, the component should be set as a:
Loading...
Usage with styled
Any of these MUI approaches can then be used with styled:
Loading...