How to use Sanitizer API in React?

225 Views Asked by At

I need to sanitize an HTML string before sending it to the backend and I'm trying to use the Sanitizer API mentioned in the Mozilla documentation. So I've created the following method in my React project:

sanitizeText(unsanitized_string) {
    return new Sanitizer().sanitizeFor(
        "div",
        unsanitized_string,
    ).innerHTML;
}

But this is having the following compilation error:

Line 94:20: 'Sanitizer' is not defined no-undef

Why am I getting this error?

1

There are 1 best solutions below

1
Wing On BEST ANSWER

Problem

At the time of writing HTML Sanitizer API is still experimental. The error in the question looks like a linting error (no-undef). I assume it's from ESLint. ESLint gets a list of globals from this package. Looking in the package's definition of global variables, the HTML Sanitizer API does not appear. It also doesn't appear to have guidelines for contributing missing types (see TypeScript's DOM Lib Generator repo for something similar) so it's not certain how global variables get in or if there's a baseline of support required for an API.

Solution

Configuring ESLint

You could make ESLint aware of the global variable. There are several options:

Using a configuration comment

At the top of files referencing the global you could add the following:

/* global Sanitizer */

Demo

Using a configuration file

In ESLint's configuration file you could add the following:

{
  "globals": {
    "Sanitizer": true
  }
}

See documentation for more details.

Contributing to the globals package

You could head to the globals package and open an issue to inquire about adding new globals. The package author may elaborate on contribution guidelines (such as a baseline for support). If they're open to contributions, you could add the definition yourself.