Repozytorium Web Developera

React Refs

Useful links

Get reference to your component

You can get a reference to an element by using ref property. When you use class component you can easily set a reference to choosen element by setting on it the prop ref={el => { this.el = el }} and then you will be able to access it properties, for example in component lifecycle methods to focus it by use this.el.focus().


class Input extends Component {
  focus () {
    this.el.focus()
  }
  
  render () {
    return (
      <input
        ref={el => { this.el = el }}
      />
    )
  }
}

createRef API

React 16.3 introduces new way to manage refs. Blog post


class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.inputRef = React.createRef();
  }

  render() {
    return <input type="text" ref={this.inputRef} />;
  }

  componentDidMount() {
    this.inputRef.current.focus();
  }
}

forwardRef API

forwardRef introduced in React 16.3 can be used to pass refs to another components. Blog post


function withTheme(Component) {
  // Note the second param "ref" provided by React.forwardRef.
  // We can attach this to Component directly.
  function ThemedComponent(props, ref) {
    return (
      <ThemeContext.Consumer>
        {theme => (
          <Component {...props} ref={ref} theme={theme} />
        )}
      </ThemeContext.Consumer>
    );
  }

  // These next lines are not necessary,
  // But they do give the component a better display name in DevTools,
  // e.g. "ForwardRef(withTheme(MyComponent))"
  const name = Component.displayName || Component.name;
  ThemedComponent.displayName = `withTheme(${name})`;

  // Tell React to pass the "ref" to ThemedComponent.
  return React.forwardRef(ThemedComponent);
}

const fancyButtonRef = React.createRef();

// fancyButtonRef will now point to FancyButton
<FancyThemedButton
  label="Click me!"
  onClick={handleClick}
  ref={fancyButtonRef}
/>;