This is my example for react router, I think the examples on their website could be better. This is react router 4, which I really like the direction they took. More Description will follow later.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link,} from 'react-router-dom'; import Products from './Products' const Home = () => ( <div> <h2>Home</h2> </div> ); class App extends Component { constructor() { super(); this.state = { products: null }; } loadProducts = () => { return new Promise(resolve => { setTimeout(function(){ resolve( [{id:1, name:'Tesla S1'}, {id:2,name:'Tesla S2'}] ); }, 1000); }).then(products => this.setState({ products })); }; render() { return ( <Router> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/products">Products</Link></li> </ul> <hr/> <Route exact path="/" component={Home} /> <Route path="/products" render={() => <Products fetch={this.loadProducts} list={this.state.products} />} /> </div> </Router> ); } } export default App; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import React, { Component } from 'react'; import { Route, Link,} from 'react-router-dom'; import Product from './Product' class Products extends Component { componentDidMount() { if (this.props.list == null) { this.props.fetch(); } } render() { const { list } = this.props; if (list == null) { return <p>Loading...</p>; } return ( <div> <h2>Products</h2> <ul> {list.map(product => <li key={product.id}><Link to={"/products/" + product.id}>{product.name}</Link></li>)} </ul> <div><Route path="/products/:id" render={({match}) => <Product match={match}/>} /></div> </div> ); } } export default Products; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import React, { Component } from 'react'; class Product extends Component { componentDidMount(){ console.log('component mounted ' + this.props.match.params.id); } componentDidUpdate(){ console.log('component updated ' + this.props.match.params.id); } render() { return( <div>{this.props.match.params.id}</div>); } } export default Product; |