I\'m having trouble understanding what refs are in React. I understand that it\'s a callback function and you put it in the render function, but beyond that I can\'t understand
React has typical way of handling children. It does it with use of props
in a top-down way. And to modify the child you have to re-render with new props. But there are cases where you want to modify/handle child outside of this typical flow. In these cases you use refs.
Ref is an attribute that takes a callback and this callback is called whenever the component is mounted or unmounted. Refs can be added to both dom elements or components. Example:
return (
{ this.textInput = input; }} />
);
return (
{ this.childComponent = component; }}
{...props}
/>
);
Whenever the component is mounted the ref callback is called with dom element or the child component instance. And whenever the component is unmounted its called with null
.
Now you can use this.textInput
or this.childComponent
and call its different available methods on it.
Refs can be given to only either DOM elements or class component. They don't work on functional components. Example:
function MyFunctionalComponent(props) {
return ;
}
return (
{ this.childComponent = component; }}
{...props}
/>
);
Refs should be used only when its absolutely necessary as they give you direct access to the element/component in DOM.