-
-
Save leecade/3528c1c211e2ff287d92f36cf1498b88 to your computer and use it in GitHub Desktop.
React Router 4 workaround for Link, Match, etc. inside pure component or Redux connect.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import BrowserHistory from 'react-history/BrowserHistory' | |
import React from 'react'; | |
import Test from './Test'; | |
import { Provider as Redux } from 'react-redux'; | |
import { StaticRouter } from 'react-router'; | |
import { connect } from 'react-redux'; | |
import { setLocation } from '../../common/app/actions'; | |
// Some component wrapped by pure container. | |
const Test = (props) => ( | |
<div> | |
<Link activeOnlyWhenExact activeStyle={{ color: 'red' }} to="/">home</Link> | |
<Link activeStyle={{ color: 'red' }} to="/firebase">firebase</Link> | |
<Match pattern="/firebase" component={<div>firebase</div>} /> | |
</div> | |
); | |
// Yeah, connect is pure container. | |
export default connect(state => ({ | |
// location: state.app.location, | |
currentLocale: state.intl.currentLocale, | |
currentTheme: state.themes.currentTheme, | |
}))(Test); | |
// Root2? Yeah, we need to pass pathname as provider key to FIX THINGS. | |
let Root2 = ({ dispatch, pathname }) => { | |
return ( | |
<BrowserHistory key={pathname}> | |
{({ history, action, location }) => { | |
// This smells, but I don't know how to do it better. | |
setTimeout(() => { | |
dispatch(setLocation(location)) | |
}, 0) | |
return ( | |
<StaticRouter | |
action={action} | |
location={location} | |
onPush={history.push} | |
onReplace={history.replace} | |
blockTransitions={history.block} | |
> | |
<Test /> | |
</StaticRouter> | |
) | |
}} | |
</BrowserHistory> | |
); | |
}; | |
Root2 = connect(state => ({ | |
// Use current pathname to enforce provider rerender to update context. | |
pathname: state.app.location && state.app.location.pathname, | |
}))(Root2); | |
// Root component is the must for vanilla hot reloading. | |
// Using HMR Directly: medium.com/@dan_abramov/hot-reloading-in-react-1140438583bf | |
const Root = ({ store }: Props) => { | |
return ( | |
<Redux store={store}> | |
<Root2 /> | |
</Redux> | |
); | |
}; | |
Root.propTypes = { | |
store: React.PropTypes.object.isRequired, | |
}; | |
export default Root; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment