Last active
April 24, 2016 08:27
-
-
Save franzwong/e9a1fc746eac15f722fd966d4b9cb61a to your computer and use it in GitHub Desktop.
redux router example
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 React, { PropTypes } from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { createStore, combineReducers } from 'redux' | |
import { Provider, connect } from 'react-redux'; | |
import { Link, Router, Route, IndexRoute, browserHistory } from 'react-router' | |
import { syncHistoryWithStore, routerReducer } from 'react-router-redux' | |
const reducer = combineReducers({ | |
products: (state = []) => state, | |
routing: routerReducer | |
}); | |
const store = createStore( | |
reducer, { | |
products: [{ | |
id: 1, | |
name: 'Product A', | |
price: 1000 | |
}, { | |
id: 2, | |
name: 'Product B', | |
price: 2000 | |
}] | |
} | |
); | |
const history = syncHistoryWithStore(browserHistory, store); | |
const Home = () => ( | |
<div> | |
<h1>Home</h1> | |
</div> | |
); | |
class Product extends React.Component { | |
render() { | |
let product = this.props.products.filter(product => parseInt(this.props.params.product) === product.id)[0]; | |
return (<div>Product Name: {product.name}</div>); | |
} | |
} | |
class Products extends React.Component { | |
render() { | |
return ( | |
<div> | |
<h1>Products</h1> | |
<ul> | |
{this.props.children || | |
this.props.products.map(product => ( | |
<li key={product.id}> | |
<Link to={`/products/${product.id}`} >{product.name}</Link> | |
</li>))} | |
</ul> | |
</div> | |
); | |
} | |
} | |
const mapStateToProps = (state) => { | |
return { | |
products: state.products | |
} | |
}; | |
const ProductContainer = connect( | |
mapStateToProps | |
)(Product) | |
const ProductsContainer = connect( | |
mapStateToProps | |
)(Products) | |
const Contact = () => ( | |
<div> | |
<h1>Contact</h1> | |
</div> | |
); | |
const App = ({children}) => ( | |
<div> | |
<header> | |
<Link to="/">Home</Link> | |
{' '} | |
<Link to="/products">Products</Link> | |
{' '} | |
<Link to="/contact">Contact</Link> | |
</header> | |
<div> | |
{children} | |
</div> | |
</div> | |
); | |
ReactDOM.render( | |
<Provider store={store}> | |
{ /* Tell the Router to use our enhanced history */ } | |
<Router history={history}> | |
<Route path="/" component={App}> | |
<IndexRoute component={Home}/> | |
<Route path="products" component={ProductsContainer}> | |
<Route path=":product" component={ProductContainer}/> | |
</Route> | |
<Route path="contact" component={Contact}/> | |
</Route> | |
</Router> | |
</Provider>, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment