Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flow type React ref callback and createRef

class Component extends React.Component<ComponentProps> {
  // ...magic
  elementRef = React.createRef();

  render() {
    return this.props.children(this.elementRef);
  }
}

This is a component I have. Its basically passing the ref callback to children. and then its used like this

<Component>
  {elementRef => (
    <div ref={elementRef} />
  )}
</Component>

The intention of my Component is that the children can attach the elementRef to any element.

But I having a lot of trouble type my component correctly.

What I am doing right now:

type ComponentProps = {
  +children: (
    ref: { current: HTMLDivElement | null } | ((ref: ?HTMLDivElement) => void)
  ) => React.Node,
};

But obviously this only works for div. If I were to use the elementRef on a span. Flow would complain.

So how should I type my Component correctly so that it works for any HTML element?

like image 511
xiaofan2406 Avatar asked Apr 18 '18 10:04

xiaofan2406


People also ask

What is callback REF IN React?

Callback RefsThe function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. The example below implements a common pattern: using the ref callback to store a reference to a DOM node in an instance property. class CustomTextInput extends React.

What is the difference between useRef and createRef?

useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render. It persists the existing ref between re-renders. createRef: The createRef is a function that creates a new ref every time.

What type does createRef return?

This method is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM. If we pass a ref object to any DOM element, then the. current property to the corresponding DOM node elements will be added whenever the node changes.

Why ref is not recommended in React?

We should not use ref attribute on function components because they do not have instances. React will assign the current property with Dom element when component mount and assign null to it when component unmount. ref updates happen before componentDidMount or componentDidUpdate methods.


1 Answers

I think this might solve your problem. It's not yet in the docs.

{current: null | React$ElementRef<ElementType>}
like image 170
frontsideair Avatar answered Sep 19 '22 07:09

frontsideair