Skip to content

Instantly share code, notes, and snippets.

@steida
Created September 15, 2016 00:09
Show Gist options
  • Save steida/69233478c2537ff09c28450e2d226ccf to your computer and use it in GitHub Desktop.
Save steida/69233478c2537ff09c28450e2d226ccf to your computer and use it in GitHub Desktop.
React Router 4 workaround for Link, Match, etc. inside pure component or Redux connect.
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