danday74
danday74

Reputation: 57016

migrating react-router v2 to v4 onEnter arguments

I am migrating an app (not written by me) from react-router v2 to v4.

The old v2 code looks like this:

<Route path="/configurations/:id" onEnter={loadConfiguration}>
    // some stuff
</Route>

The new v4 code looks like this:

<Route path="/configurations/:id" component={MyComponent}>
    // some stuff
</Route>

export default class MyComponent extends Component {
  componentDidMount() {
    loadConfiguration()
  }
  // render method, etc
}

The problem is that in v2 the loadConfiguration function is called with 3 params - nextState, replace, callback

In the v4 code the loadConfiguration function is called with 0 params.

How do I pass the same values to loadConfiguration when migrating from v2 to v4?

Upvotes: 0

Views: 175

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

You can use render to pass props to your component:

<Route path="/configurations/:id" render={
  () => <MyComponent nextState={ nextState } replace={ replace } callback={ callback } />
} />

And then in your component:

export default class MyComponent extends Component {

  loadConfiguration() {
    ...
  }

  componentDidMount() {
    this.loadConfiguration(this.props.example, this.props.replace, this.props.callback)
  }

  // render method, etc

}

You could also pass down the loadConfiguration function from the parent as a prop, if need be, and then call it in your component as this.props.loadConfiguration()


Note: you can also pass props from the parent:

<Route path="/configurations/:id" render={
  (props) => <MyComponent example={ props.example } />
} />

Upvotes: 1

Related Questions