Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Refs, React and Redux

Refs, React and Redux

How to use Refs on diferentes escenarios and what to do when handling connected components to Redux


When working on a React & Redux project when have 3 diferents escenarios when using refs. But first...

What is it ?

Refs are a way of storing references to an object, these refenrences can be DOM nodes or class components. It provide a way to access DOM nodes or React elements created in the render method.

DOM elements

When the ref attribute is used on an HTML element, the ref created receives the DOM element as its current property.

class Video extends React.Component {
  state = {
   isPlaying: false,
  }
  
  handleVideoClick = () => {
    if (this.state.isPlaying) {
      this.video.pause()
    }
    else {
      this.video.play()
    }
    this.setState((state) => ({ isPlaying: !state.isPlaying }))
  }
  
  togglePlay = () => {
    this.handleVideoClick()
  }
  
  render() {
    return (
      <div>
        <video
          ref={video => this.video = video}
          onClick={this.handleVideoClick}
        >
         <source
            src="some.url"
            type="video/ogg"
         />
        </video>
      </div>
    )
  }
}

play() and pause() methods live on the HTML5 video element, in order to have access to these methods we need to create a ref to the video element.

Class components

When the ref attribute is used on an class component declaration, the ref created receives the class instance, having access to the component state and methods.

class Player extends React.Component {
  constructor(props) {
    super(props)
    this.videoComp = React.createRef()
  }

  componentDidMount() {
    this.videoComp.togglePlay()
  }

  render() {
    return (
      <Video ref={this.videoComp} />
    )
  }
}

Here we have access to the video component togglePlay method and we execute this from the parent component, we can eve read the state. Basically it give us access to the entire video class instance.

Connected components

What if the component we are trying to get the ref to is connected to a Redux store via the React-Redux connect(), Redux comes with a handy way to do this:

connect(
  mapStateToProps,
  mapDispatchToProps,
  null,
  { forwardRef: true }
)(MyComponent)

Then we can use refs like a normal React component. (react-redux >= v6.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment