Skip to content

Latest commit

 

History

History
29 lines (21 loc) · 1.4 KB

v2.4.0.md

File metadata and controls

29 lines (21 loc) · 1.4 KB

v2.4.0 Upgrade Guide

withRouter HoC (higher-order component)

Prior to 2.4.0, you could access the router object via this.context. This is still true, but context is often times a difficult and error-prone API to work with.

In order to more easily access the router object, a withRouter higher-order component has been added as the new primary means of access. As with other HoCs, it is usable on any React Component of any type (React.createClass, ES2015 React.Component classes, stateless functional components).

import React from 'react'
import { withRouter } from 'react-router'

const Page = React.createClass({
  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, () => {
      if (this.state.unsaved)
        return 'You have unsaved information, are you sure you want to leave this page?'
    })
  },

  render() {
    return <div>Stuff</div>
  }
})

export default withRouter(Page)

It's important to note this is not a deprecation of the context API. As long as React supports this.context in its current form, any code written for that API will continue to work. We will continue to use it internally and you can continue to write in that format, if you want. We think this new HoC is nicer and easier, and will be using it in documentation and examples, but it is not a hard requirement to switch.