0

I´ve checked the following post and although it gives several different solutions not of them seens to solve my problem.

Using react-router V4 I need to programatically navigate from components deep insider my tree that will not have access to router props passed (history, url, params, etc.). What is the most straightfoward way of doing it ?

Mendes
  • 17,489
  • 35
  • 150
  • 263
  • What have you tried? Do you get an error when trying `this.context.router.transitionTo` or `this.props.history.push`? – Scott Oct 24 '17 at 01:03

2 Answers2

1

The most straight forward way is to move history into separate file like so

history.js:

import createHistory from 'history/createBrowserHistory'
const history = createHistory()
export default history

and then in any other component:

import history from 'path/to/history.js'

...
someFoo(){
  history.push({
    pathname: '/new/url',
  })
}
...

You also need to make sure you pass new history to your router to make it work

Max Gram
  • 685
  • 4
  • 14
  • What do you mean by "You also need to make sure you pass new history to your router to make it work" I've tried this and the history changes but the component doesn't changed as it will if I I was using `Link` – Leonel Galán Nov 14 '17 at 01:40
  • That's probably because you have 2 instances of history. Most likely you need to reference the same history on your router, for example `import history from 'path/to/history.js' ` – Max Gram Nov 14 '17 at 23:51
1

Any component in your tree, irrespective of its depth, can get access to the history, location and match props which are used by react-router. To do this you have to wrap the component in the withRouter HOC provided by react-router.

Code:

//other imports
import {withRouter} from 'react-router-dom'

//define component MyComponent here

export default withRouter(MyComponent);

Inside MyComponent defined above, you can access the history prop and redirect to any new url by using this.props.history.push(newURL); You can find more information at https://reacttraining.com/react-router/web/api/withRouter

palsrealm
  • 5,083
  • 1
  • 20
  • 25
  • What about the options related to `shouldComponentUpdate`, like: `// This gets around shouldComponentUpdate withRouter(connect(...)(MyComponent)) // This does not connect(...)(withRouter(MyComponent))` - What are they used for ? – Mendes Oct 24 '17 at 09:42
  • you should ask that to @ShubhamKhatri who answered that question. Or you can post another question. :) – palsrealm Oct 24 '17 at 14:52