SolidJSS
SolidJSโ€ข16mo agoโ€ข
6 replies
zobweyt

Using JSX in custom directives

Suppose you want to create a convenient tooltip directive that can be easily used by providing only the content of it. This works fine for simple tooltips. However, what if you want to create more complex, custom tooltips? For example, you want to wrap the element as a trigger and use it in combination with a component from libraries like https://kobalte.dev/docs/core/components/tooltip or https://corvu.dev/docs/primitives/tooltip

import { type Accessor, createEffect, createSignal } from "solid-js";
import { render } from "solid-js/web";

export default function tooltip(el: HTMLElement, title: Accessor<string>) {
  createEffect(() => {
    el.title = title();
  });
}

declare module "solid-js" {
  namespace JSX {
    interface DirectiveFunctions {
      tooltip: typeof tooltip;
    }
  }
}

function App() {
  const [count, setCount] = createSignal<number>(0);

  return (
    <button
      onClick={() => setCount((c) => c + 1)}
      use:tooltip="Push to increment count"
    >
      {count()}
    </button>
  );
}

render(() => <App />, document.getElementById("app")!);

https://playground.solidjs.com/anonymous/eb41151c-59ca-460f-aa45-26ea80525e01

Is it possible to use JSX inside the directive to wrap the <button> with a <Tooltip> component?
Was this page helpful?