score:0

you can only pass one ref object into the child, but i don't think that should be a problem. both you and whoever uses your component should be able to access and use the same ref object.

so you'll just need to check if you were given a ref, and if not create your own. since hooks need to be called consistently, you'd want to always call useref, and then just sometimes use the passed in ref instead:

export default forwardref<htmlinputelement, props>(({ label, ...props }, ref) => {
  const id = useid();
  const inputref = useref(null);
  ref = ref || inputref;
  // ... more mechanics here, all referencing `ref`, not `inputref`
  return (
    <div>
      <label htmlfor={id}>{label}</label>
      <input {...props} id={id} ref={ref} />
    </div>
  );
});

score:0

you can use a callback ref to get the reference to the underlying node, and set both the passed ref and the input ref's current node.

export default forwardref<htmlinputelement, props>(
  ({ label, ...props }, ref) => {
    const id = useid();
    const inputref = useref(null);

    const setbothrefs = node => {
      ref = node;
      inputref.current = node;

      console.log(`inputref`, inputref, `ref=>`, ref);
    };

    return (
      <div>
        <label htmlfor={id}>{label}</label>
        <input {...props} id={id} ref={setbothrefs} />
      </div>
    );
  }
);

Related Query

More Query from same tag