Owl
Owl

Reputation: 6853

Passing directive as props

For example I have a simple directive like this:

export const inputLogger = (el: HTMLInputElement) => {
    const onInput = (e: Event) => {
        console.log((e.currentTarget as HTMLInputElement).value)
    }

    el.addEventListener("input", onInput);
};

and my component looks like this

const CustomInput: Component<JSX.InputHTMLAttributes<HTMLInputElement>> = (props) => {
  return <input {...props} />
}

function Counter() {
  return (
    <>
      <CustomInput use:inputLogger  />  {/* directive is not being used */}
      <br />
      <input use:inputLogger /> {/* directive works properly */}
    </>
  );
}

Seems like inputLogger directive doesn't work properly when being passed as a prop to other component, but works fine when passed to a native input element.

Am I doing something wrong? Is there a workaround for this or is this a limitation from Solid.js?

Playground Example

Upvotes: 3

Views: 912

Answers (1)

FoolsWisdom
FoolsWisdom

Reputation: 1061

Unfortunately, in Solid, directives can only be applied to native elements, not to components. See here: https://www.solidjs.com/tutorial/bindings_directives.

You can also use a pattern like this, but you no longer can rely on spreading props.

const CustomInput: Component<JSX.InputHTMLAttributes<HTMLInputElement>> = (
  props
) => {
  return <input {...props} ref={props["use:inputLogger"]} />;
};

function Counter() {
  return (
    <>
      <CustomInput use:inputLogger={inputLogger} />
    </>
  );
}

https://playground.solidjs.com/?hash=-51759678&version=1.4.1

Upvotes: 3

Related Questions