javascriptweb-componentlit-elementlit-html

Error when using unsafeHTML with lit-element


This is my code:

import {customElement, LitElement, html, property, css} from 'lit-element';
import {unsafeHTML} from 'lit-html/directives/unsafe-html.js';

@customElement('my-component')
export class myComponent extends LitElement {
  render() {
    const markup = '<div>Some HTML to render.</div>';
    return html`
      ${unsafeHTML(markup)}
    `;
  }
}

But when I run on browser, I get an error like this:

part => { if (!(part instanceof NodePart)) { throw new Error('unsafeHTML can only be used in text bindings'); } const previousValue = previousValues.get(part); if (previousValue !== undefined && isPrimitive(value) && value === previousValue.value && part.value === previousValue.fragment) { return; } const template = document.createElement('template'); template.innerHTML = value; // innerHTML casts to string internally const fragment = document.importNode(template.content, true); part.setValue(fragment); previousValues.set(part, { value, fragment }); }

enter image description here

My code is so simple but I still got the error, so can anyone suggest to me, how to make it work.


Solution

  • This type of error is often caused by multiple versions of lit-html interacting in the same project. A common scenario is when you start using LitElement (which internally uses a version of lit-html) and then install lit-html separately to be able to use the built-in directives. This sometimes can result in a duplication, easily fixable by running

    $ npm dedupe
    

    Also, for yarn users:

    $ yarn install --flat
    

    can be of help in this case.