EN
TypeScript / React - safe link to external web page
8
points
In this short article, we woudl like to show how to create safe link to external web page using React.
Practical example:
App.tsx
file:
import React from 'React';
import ExternalLink from './ExternalLink';
const App = () => {
return (
<div>
<ExternalLink url="https://wikipedia.org">Wikipedia</ExternalLink>
<ExternalLink url="https://google.com" window={true}>Google</ExternalLink>
<ExternalLink url="https://facebook.com" title="Facebook Web Site">Facebook</ExternalLink>
</div>
);
};
export default App;
ExternalLink.tsx
file:
import React, {ReactNode} from 'React';
import style from './style.scss';
const NEUTRAL_URL: string = 'javascript: void (0)';
export type Props = {
/** url that should be open by link */
url?: string;
/** title that describes link */
title?: string;
/** indicates if link should be open in the new window */
window?: true;
/** link content */
children?: ReactNode;
};
/**
* Creates safe external link component that do not send referer information.
*
* It is very important to prevent againts access from opened page to opener in Javascript code.
* The solution is to add rel="noopener noreferrer" to the link (it is supported by Chrome, Firefox and Internet Explorer).
*
* Read more:
* https://html.spec.whatwg.org/multipage/links.html#link-type-noreferrer
* https://dirask.com/posts/JavaScript-open-link-in-new-tab-1bBP41
* https://dirask.com/findings/DLo9E1
*/
const ExternalLink = ({url, title, window, children}: Props): JSX.Element =>
(
<a className={style.link} rel="noopener noreferrer" href={url ?? NEUTRAL_URL} title={title} target={window ? '_blank' : undefined}>
{children}
</a>
);
export default ExternalLink;