Skip to content

Instantly share code, notes, and snippets.

@keyserfaty
Last active September 8, 2016 18:15
Show Gist options
  • Select an option

  • Save keyserfaty/cf609e6b724542897457609f3f6e15df to your computer and use it in GitHub Desktop.

Select an option

Save keyserfaty/cf609e6b724542897457609f3f6e15df to your computer and use it in GitHub Desktop.
Handling refs in React with ES6 classes

What are React's refs?

Refs are a reference to the DOM node created by a React element after rendering. There are some scenarios when you need to operate on the node element (the actual DOM node that is rendered to the view) rather than the element used by React in the virtual DOM. My case scenario: I needed to let the user download an image that was generated with a canvas in the virtual DOM. The only way to do this was to wait for the page to be fully rendered and do some stuff on the canva's node element.

With ref you can access the node element that an element from the virtual DOM will generate after its done, like this:

render() {
  return (
    <span className='container' ref='cont'>Container!</span>
  );
}

Now, after the element is mounted of course you can do something like this:

componentDidMount() {
  const contNode = this.refs.cont;
  // Do stuff!
}

How to work with refs in ES6 classes?

There are some great tutorials online on how to use the ref attribute in an element but many of them use code not longer available in react > 0.14.

Some stuff you might read around that won't work anymore:

  • this.isMounted: won't work with ES6 classes as stated in here.
  • React.findDOMNode: was replace with ReactDOM.findDOMNode.
  • And one more thing: you won't be able to use the ref attr in pure functions. There will have to be classes. A link here.

###How to actually do it

According to react's documentation on the ref attribute there are two ways of handling a ref reference (hehem):

  • Defining a name to the ref like this: <input type="text" ref="myInput">.
  • Defining a function to be executed after the node is mounted, likes this: <input type="text" ref="this.doOnMounted">.

###A full example

To keep it simple and short here is a fully working example of how to do it:

class MyComponent extends Component {
  constructor (props) {
    super(props);
    this.state = {
      thing: ''
    };
    this.onMounted = this.onMounted.bind(this);
  }

  onMounted (c) {
    const refsExists = c => c != null;
    
    if (refsExists(c)) {
      // Do stuff with `c.refs`
    }
  }

  render () {
    const { thing } = this.state;
    const { onMounted } = this;

    return (
      <span ref={onMounted}>
        {thing}
      </span>
    );
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment