DEV Community

Cover image for Day 9 - What is ref in react?
C K Sanjay Babu
C K Sanjay Babu

Posted on • Originally published at blog.sanjaybabu.dev on

Day 9 - What is ref in react?

In react, Refs provide a way to access or reference the DOM element from within a parent component. Generally, in react, we would use props for any interactions between the components. We can re-render the component with updated props to modify it. Refs provide a way to imperatively do this change.

When to use Refs?

According to react documentation,

  • Manage focus, text selection, or media playback.
  • Perform imperative animations.
  • Integrate with third-party DOM libraries.

When not to use Refs?

We use a library like react for its declarative programming style. We just specify this or that needs to be done and the react handles it. But when the ref provides us the flexibility of imperative control. Hence these should not be overused.

Example

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Refs are so useful they have solved so many problems for me in the past when working on React projects.

Collapse
 
sanjaybabu profile image
C K Sanjay Babu • Edited

Refs saved my day once when I was working with animations, other than havent used it much personally!
But they surely are really useful in few peculiar cases.