Skip to content

Instantly share code, notes, and snippets.

@vschoettke
Created March 14, 2017 09:58
Show Gist options
  • Save vschoettke/9d7440e1580fa2017d733f1df71ff9a5 to your computer and use it in GitHub Desktop.
Save vschoettke/9d7440e1580fa2017d733f1df71ff9a5 to your computer and use it in GitHub Desktop.
Simple Example to demonstrate problem with react-redux connect() function and react-router v4
// Example of non-working react-router v4
// If <Router> is moved into BasicExample
// OR
// redux connect() call is removed routing will work again
// Tested with:
// ├─ [email protected]
// ├─ [email protected]
// │ ├─ hoist-non-react-statics@^1.0.3
// ├─ [email protected]
// │ └─ react-router@^4.0.0
// ├─ [email protected]
// ├─ [email protected]
// ├─ [email protected]
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {createStore} from 'redux';
import {Provider, connect} from 'react-redux';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
function testReducer(state = {}, action = {}) {
return Object.assign({}, state, {
test: "redux store data"
});
}
const store = createStore(testReducer);
// <Router> moved to parent component
const BasicExampleOrg = ({test = "no redux connect?"}) => (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<hr/>
<pre>{JSON.stringify(test, null, 4)}</pre>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
</div>
)
function mapStateToProps(state) {
return {
test: state.test,
};
}
const BasicExample = connect(
mapStateToProps
)(BasicExampleOrg);
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<BasicExample />
</Router>
</Provider>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment