PonchoP
Deno4y ago
Poncho

How to forward a reference to a component

I created this sample to exemplify what I don't understand. Using the Fresh framework, I created the following Input component:
import { JSX } from "preact";

interface Input
  extends JSX.HTMLAttributes<HTMLInputElement>, Partial<GlobalEventHandlers> {
  label?: string;
}

export default function (props: Input) {
  const { label } = props;
  return (
    <div class="container">
      <span>{label}</span>
      <input type="text" {...props} />
    </div>
  );
}


Inside of an island, I know I can add events listeners to the
<input />
element inside the Input component thanks to the spreading of the rest of the props (
{...props}
). But when I try to add a reference to it, like so:
import { useRef } from "preact/hooks";
import Input from "../components/Input.tsx";

export default function () {
  const refInput = useRef<HTMLInputElement>(null);

  return (
    <div>
      <Input ref={refInput}></Input>
    </div>
  );
}

The reference is not forwarded to the
<input />
element, instead it targets what I suppose is a component object of some sort. Definitely, the reference doesn't target the
HTMLInputElement
as it should. I believe I'm forwarding the reference in an incorrect way. The attached image is what
console.log(refInput.current)
logs.

Thanks in advance
Screen_Shot_2022-12-12_at_13.57.08.png
Was this page helpful?