Day 9 - What is ref in react?

sanjaybabu

C K Sanjay Babu

Posted on May 9, 2022

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
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
sanjaybabu
C K Sanjay Babu

Posted on May 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About