Day 9 - What is ref in react?

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.


class CustomTextInput extends React.Component {
  constructor(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

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