Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 19 "ref as prop" and TypeScript

React 19 introduces a new alternative to the existing forwardRef that is called ref as prop:

https://react.dev/blog/2024/12/05/react-19#ref-as-a-prop

But unfortunately the example provided in the blog post is written in JavaScript, not TypeScript:

function MyInput({ placeholder, ref }) {
  return <input placeholder={placeholder} ref={ref} />
}

//...
<MyInput ref={ref} />

So in TypeScript, what is the correct type the ref prop?

like image 317
Mir-Ismaili Avatar asked Dec 03 '25 15:12

Mir-Ismaili


2 Answers

It seems React.RefObject is NOT correct. But React.Ref is the correct choice:

import type {Ref} from 'react'

function MyInput({placeholder, ref}: {placeholder?: string; ref?: Ref<HTMLInputElement>}) {
  return <input placeholder={placeholder} ref={ref} />
}
function MyComponent() {
  const ref = useRef<HTMLInputElement>(null)
  return <MyInput ref={ref} /> // OK
}

Don't forget mark it as optional (ref?: Ref<...>).


In more complex situations —such as my real case where I used @lexical/[email protected], which appears to not completely compatible with React 19— I wrote the ref like this:

function RichTextEditor({ref}: {ref?: Ref<LexicalEditor>}) {
  // ...
  return (
    // ...
      <EditorRefPlugin
        editorRef={(editorRef) => {
          if (!ref) return
          if (typeof ref === 'function') ref(editorRef)
          else ref.current = editorRef
        }}
      />
    // ...
  )
}
like image 129
Mir-Ismaili Avatar answered Dec 06 '25 07:12

Mir-Ismaili


Use React.RefObject:

function MyInput({placeholder, ref}: {
  placeholder: string;
  ref: React.RefObject<HTMLInputElement>;
}) {
  return <input placeholder={placeholder} ref={ref} />
}
like image 34
Michał Perłakowski Avatar answered Dec 06 '25 08:12

Michał Perłakowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!