-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathSafeAnchor.tsx
40 lines (37 loc) · 1.26 KB
/
SafeAnchor.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React, { PropsWithChildren } from 'react';
import { sanitizeUrl } from '@braintree/sanitize-url';
import { useTranslationContext } from '../../context';
/**
* Similar to a regular anchor tag, but it sanitizes the href value and prevents XSS
*/
export type SafeAnchorProps = {
/** Set the className for the anchor tag element */
className?: string;
/** Specifies that the target (href attribute) will be downloaded instead of navigating to a file */
download?: boolean;
/** Set the href attribute for the anchor tag element */
href?: string;
/** Set the rel attribute for the anchor tag element */
rel?: string;
/** Set the target attribute for the anchor tag element */
target?: string;
};
const UnMemoizedSafeAnchor = (props: PropsWithChildren<SafeAnchorProps>) => {
const { children, className, download, href, rel, target } = props;
const { t } = useTranslationContext('SafeAnchor');
if (!href) return null;
const sanitized = sanitizeUrl(href);
return (
<a
aria-label={t('aria/Attachment')}
className={className}
download={download}
href={sanitized}
rel={rel}
target={target}
>
{children}
</a>
);
};
export const SafeAnchor = React.memo(UnMemoizedSafeAnchor) as typeof UnMemoizedSafeAnchor;