Skip to content

Instantly share code, notes, and snippets.

@predragnikolic
Created October 18, 2022 10:24
Show Gist options
  • Save predragnikolic/1a8d606b90f1f2e679cbc41d3a0577f2 to your computer and use it in GitHub Desktop.
Save predragnikolic/1a8d606b90f1f2e679cbc41d3a0577f2 to your computer and use it in GitHub Desktop.
/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable jsx-a11y/anchor-has-content */
import { Trans } from "react-i18next"
const ALLOWED_TAGS = {
"a": <a />,
"b": <b />,
"i": <i />,
"u": <u />,
"s": <s />,
"ul": <ul />,
"li": <li />,
"em": <em />,
"span": <span />,
"div": <div />
}
/**
* This component replaces the use of `dangerouslySetInnerHTML`.
*/
type Props = {
htmlString: string
}
export function SafeHtml({ htmlString }: Props) {
// We use the Trans component from i18n, because i18n can safely set the html.
//
// A different solution would involve installing a different dependency, for example `sanitizeHtml`
// https://stackoverflow.com/questions/38663751/how-to-safely-render-html-in-react#answer-38663813
return <Trans
shouldUnescape
defaults={htmlString.replaceAll("&nbsp;", " ")}
components={ALLOWED_TAGS} />
}
@predragnikolic
Copy link
Author

depends on "react-i18next": "^11.15.1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment