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?
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.
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.
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.
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.
I think this might solve your problem. It's not yet in the docs.
{current: null | React$ElementRef<ElementType>}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With