To further ellaborate on Samuel Tosin's response,
If you set up a new project using npm create vite@latest (React 19, but should work with React 17 and 18), you can create the following function component:
import React from "react";
export type CustomAnchorProps = React.AnchorHTMLAttributes<HTMLAnchorElement> & {
external?: boolean;
};
const CustomAnchor: React.FC<CustomAnchorProps> = ({
children,
className = "",
external = false,
target,
rel,
...rest
}) => {
return (
<a
{...rest}
target={external ? "_blank" : target}
rel={external ? "noopener noreferrer" : rel}
className={`CustomAnchor ${className}`}
>
{children}
</a>
);
};
export default CustomAnchor;
The component supports the base anchor attributes, plus an additiona ones defined in the CustomAnchorProps type union. Additionally, the children prop allows you to use this component to wrap anything you want.
Here is the usage (I just blew-away the default App.tsx in the Vite setup):
import CustomAnchor from "./components/CustomAnchor";
import "./App.css";
function App() {
return (
<>
<div>
<CustomAnchor href="https://example.com" external>
<h2>External Link</h2>
</CustomAnchor>
<CustomAnchor href="/about">
<h2>Internal Link</h2>
</CustomAnchor>
</div>
</>
);
}
export default App;
aelement isHTMLAnchorElement. You can find those types in this list in the HTML5 specification.