Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are refs in React?

Tags:

reactjs

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.

like image 507
ajheilman Avatar asked Oct 19 '17 00:10

ajheilman


2 Answers

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

like image 159
ACVM Avatar answered Oct 13 '22 22:10

ACVM


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.

like image 42
vs1682 Avatar answered Oct 13 '22 23:10

vs1682