2022-09-08 12:13:20 +03:00

58 lines
1.2 KiB
TypeScript

import React from "react";
import { NavLink, NavLinkProps } from "react-router-dom";
import classNames from "classnames";
type Props = {
to: string;
children: React.ReactNode;
disabled?: boolean;
className?: string;
} & NavLinkProps;
function getURL(to: string): URL {
try {
return new URL(to);
} catch {
let outurl = `${window.location.origin}${
to.startsWith("/") ? to : "/" + to
}`;
return new URL(outurl);
}
}
export default function Link({
to,
children,
disabled,
className,
style,
...props
}: Props) {
const link =
getURL(to).hostname === window.location.hostname ? (
<NavLink
to={getURL(to).pathname}
style={style}
className={classNames({ "pointer-events-none": disabled }, className)}
>
{children}
</NavLink>
) : (
<a
href={disabled ? undefined : getURL(to).origin}
style={
typeof style === "function"
? style({
isActive: true,
})
: style
}
aria-disabled={disabled}
{...props}
>
{children}
</a>
);
return <div>{link}</div>;
}