useSelf hook

How to use the useSelf hook to get the instance of the element itself.


Description

Sometimes you want to modify a custom element itself inside of it's own render function. To get the instance element, you can actually use the this keyword, but a better option is to use the useSelf hook.

This hook will simply return the instance element, but it's typescript friendly and it's safer to use, becasue the this keyword can be altered.


Usage

const self = useSelf();

The useSelf hook accepts no parameters.


An example is to add a custom class to the element based on some conditions. To do that, you can use the useSelf hook to access the element's instance.

import { defineWompo, html, useSelf } from 'wompo';

export default function InputExample({ disabled, styles: s }) {
  const self = useSelf();

  useEffect(() => {
    if (disabled) self.classList.add(s.disabled);
  }, [disabled]);

  return html`<input disabled=${disabled} />`;
}

InputExample.css = `
  .disabled {
    opacity: .7;
    cursor: not-allowed;
  }
`;

defineWompo(InputExample);