Is there a way to implement render reactivity in a Lit directive?

31 Views Asked by At

I'm using Lit 2.7.6 and am trying to implement a directive that can be used inside of a component. I tried to get a working StackBlitz example to share, but there was an issue with the imports from the lit packages that I couldn't get working.

The issue I'm encountering is that updating the isOpen property doesn't actually trigger a re-render inside of the directive, but does inside of the component. For example, if this directive was used to open a menu, the isOpen prop would change, and you could see it in a console.log, but the actual render of ${is.Open} on the page would not change.

This is my component.ts file,

import { LitElement } from 'lit-element';
import { html, TemplateResult } from 'lit';
import { property } from 'lit/decorators.js';
import { exampleDirective } from './directive';

class exampleComponent extends LitElement {
  @property({ type: Boolean })
  isOpen: boolean = false;

  render(): TemplateResult {
    const props: Object = {
      isOpen: this.isOpen,
    };

    return html`
      <div>${this.isOpen}</div>
      ${exampleDirective(props)};
    `;
  }
}

And this is my directive.ts file,

import { html, TemplateResult } from 'lit';
import { Directive, directive, PartInfo } from 'lit/directive.js';

class directiveTemplate extends Directive {
  private props: Object;

  constructor(partInfo: PartInfo) {
    super(partInfo);
  }

  update(partInfo: PartInfo, [props]: [Object]) {
    console.log(props);
    return this.render(props);
  }

  render(props: Object): TemplateResult {
    return html`<div>${props.isOpen}</div>`;
  }
}

export const exampleDirective = directive(directiveTemplate);
0

There are 0 best solutions below