React Router v4 Redirect not working
You should render only Redirect
in your render method:
render() {
return (<Redirect to="/" />);
}
but here is my favorite solution without using the Redirect
component
- import
import { withRouter } from 'react-router-dom';
export default withRouter(MyComponent);
- Finally, in your action method, assume that
handlingButtonClick
handlingButtonClick = () => {
this.props.history.push("/") //doing redirect here.
}
<Redirect />
should not be inside <Switch></Switch>
tags.
The asker posted an issue on GitHub, and got this apparently unpublished hidden guide (edit: now published) that helped me out too. I'm posting it here because I ran into the same problem and want others to avoid our pain.
The problem is that mobx-react and react-redux both supply their own shouldComponentUpdate()
functions that only check for prop changes, but react-router sends state down through the context. When the location changes, it doesn't change any props, so it doesn't trigger an update.
The way around this is to pass the location down as a prop. The above guide lists several ways to do that, but the easiest is to just wrap the container with the withRouter()
higher order component:
export default withRouter(observer(MyComponent))
or, for redux:
export default withRouter(connect(mapStateToProps)(MyComponent))
Be careful when composing the Router with other components like translation providers, theme providers, etc .. After some time I found that your App has to be strictly wrapped by the Router, like this:
<Provider store={store}>
<ThemeProvider theme={theme}>
<TranslationProvider
namespaces={['Common', 'Rental']}
translations={translations}
defaultNS={'Common'}
>
<Router>
<App />
</Router>
</TranslationProvider>
</ThemeProvider>
</Provider>
Hope this helps somebody