Skip to content

Instantly share code, notes, and snippets.

@sk22
Last active July 10, 2025 15:39
Show Gist options
  • Save sk22/9cc1a3555becba2647a1499b03cde1f0 to your computer and use it in GitHub Desktop.
Save sk22/9cc1a3555becba2647a1499b03cde1f0 to your computer and use it in GitHub Desktop.
Slim wrapper for Ant Design's Button that supports routing through React Router's `to` property, making it a replacement for invalid constructs like `<Link to="/"><Button /></Link>`
import { Button, type ButtonProps } from 'antd';
import { useCallback, type MouseEventHandler } from 'react';
import { useNavigate, useHref, type To, type NavigateOptions } from 'react-router';
export interface LinkButtonProps extends ButtonProps {
to?: To;
options?: NavigateOptions;
}
/** Wraps Ant Design's `Button` to allow and correctly handle the React Router `to` prop */
export function LinkButton({ to, options, ...btnProps }: LinkButtonProps) {
const navigate = useNavigate();
const href = useHref(to ?? '');
const handleClick: MouseEventHandler<HTMLElement> = useCallback(
(event) => {
event.preventDefault();
navigate(href, options);
},
[href, navigate, options],
);
return to ? <Button href={href} onClick={handleClick} {...btnProps} /> : <Button {...btnProps} />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment