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 what it is and what its purpose is.
Refs are a way for you to get a handle back to the component you've created.
ie.
<Text ref={(component)=>{this.textComponent = component}} > Here is some Text</Text>
Then later in your code, you can access your text by doing:
this.textComponent
This will enable you to then invoke functions on the component in a object-oriented manner.
I just want to point out that React/React-Native uses the declarative programming paradigm where data and "control" are managed through top-down passage of properties. Whereas in an imperative style you deal with objects and pointer and pass them around in order to invoke functions on them. Refs, in this case, is an escape hatch which allows you to get a declared component so that you can invoke functions on them in an imperative style.
See the official React documentation for refs: https://reactjs.org/docs/refs-and-the-dom.html
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 (
<div>
<input
type="text"
// ref to a dom element
ref={(input) => { this.textInput = input; }} />
</div>
);
return (
<MyComponent
// ref to a MyComponent(child component)
ref={(component) => { 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 <input type="text" />;
}
return (
<MyFunctionalComponent
// This won't work
ref={(component) => { 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.
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