how to define ref type by flowtype?
Note from the future:
The type for createRef
has changed, so this answer may be somewhat out-of-date. The type is now function createRef<T>(): {current: null | T}
. Everything below is retained for reference.
Taking a look at the typedef for createRef()
, we can see it returns an object with this type:
{current: null | React$ElementRef<ElementType>}
It would be a little verbose to include that every time we wanted to specify the result of createRef()
, so let's make a helper type. The React$XXX
types are supposed to be internal. So we'll use the React.XXX
types instead:
type ReactObjRef<ElementType: React.ElementType> = {current: null | React.ElementRef<ElementType>}
And then we'll use it like this:
(Try)
import * as React from 'react'type ReactObjRef<ElementType: React.ElementType> = {current: null | React.ElementRef<ElementType>}type ParentProps = {}class ParentComponent extends React.Component<ParentProps, null> { listRef: ReactObjRef<'ul'> constructor(props: ParentProps) { super(props); this.listRef = React.createRef(); } render() { return ( <ChildComponent listRef={this.listRef} /> ); }}type ChildProps = { listRef: ReactObjRef<'ul'>,};const ChildComponent = (props: ChildProps) => { const hoge = props.listRef.current; return ( <div> <ul ref={props.listRef}> </ul> </div> )}
Note it does not work for stateless functional components as described in Flow https://flow.org/en/docs/react/types/#toc-react-elementref
Beware it can happen with higher order components.