React Router v4
There's a couple of things that I needed to get this working smoothly.
The doc page on auth workflow has quite a lot of what is required.
However I had three issues
- Where does the
props.history come from?
- How do I pass it through to my component which isn't directly inside the
Route component
- What if I want other
props?
I ended up using:
- option 2 from an answer on 'Programmatically navigate using react router' - i.e. to use
<Route render> which gets you props.history which can then be passed down to the children.
- Use the
render={routeProps => <MyComponent {...props} {routeProps} />} to combine other props from this answer on 'react-router - pass props to handler component'
N.B. With the render method you have to pass through the props from the Route component explicitly. You also want to use render and not component for performance reasons (component forces a reload every time).
const App = (props) => (
<Route
path="/home"
render={routeProps => <MyComponent {...props} {...routeProps}>}
/>
)
const MyComponent = (props) => (
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
fakeAuth.signout(() => props.history.push('/foo'))
}}>Sign out</button>
)
One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match }) i.e. Object destructuring, which meant initially I didn't realise that Route passes down three props, match, location and history
I think some of the other answers here are assuming that everything is done via JavaScript classes.
Here's an example, plus if you don't need to pass any props through you can just use component
class App extends React.Component {
render () {
<Route
path="/home"
component={MyComponent}
/>
}
}
class MyComponent extends React.Component {
render () {
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
this.fakeAuth.signout(() => this.props.history.push('/foo'))
}}>Sign out</button>
}
}