Created
July 4, 2017 22:08
-
-
Save odarbelaeze/8f42961d70e272f64b95de0bda968155 to your computer and use it in GitHub Desktop.
React router basic example.
This file contains 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, { Component } from 'react'; | |
import {BrowserRouter, Route, Link} from 'react-router-dom'; | |
import logo from './logo.svg'; | |
import './App.css'; | |
const Contacto = () => ( | |
<div className="contacto"> | |
Salude no mas | |
</div> | |
); | |
const About = () => ( | |
<div className="about"> | |
Hola que hace | |
</div> | |
); | |
class User extends React.Component { | |
componentDidMount() { | |
const userId = this.props.match.params.id; | |
if (!(userId in this.props.users)) { | |
this.props.loadUser(userId); | |
} | |
} | |
render() { | |
const userId = this.props.match.params.id; | |
const user = this.props.users[userId]; | |
if (user) { | |
return ( | |
<div className="user"> | |
Listo usuario {user.id} | |
</div> | |
); | |
} | |
else { | |
return ( | |
<div className="user"> | |
Cargando usuario {userId} | |
</div> | |
); | |
} | |
} | |
} | |
const App = ({ loadUser, state }) => ( | |
<div className="App"> | |
<div className="App-header"> | |
<img src={logo} className="App-logo" alt="logo" /> | |
<h2>Welcome to React</h2> | |
</div> | |
<p className="App-intro"> | |
To get started, edit <code>src/App.js</code> and save to reload. | |
</p> | |
<nav> | |
<Link to='/contacto'>Contacto</Link> | |
<Link to='/about'>About</Link> | |
<Link to='/user/1234'>User 1234</Link> | |
</nav> | |
<Route path='/contacto' component={Contacto} /> | |
<Route path='/about' component={About} /> | |
<Route path='/user/:id' render={props => ( | |
<User {...props} loadUser={loadUser} users={state.users} /> | |
)} /> | |
</div> | |
); | |
class AppRouter extends Component { | |
constructor(props) { | |
super(props); | |
this.state = {users: {}}; | |
} | |
loadUser(id) { | |
console.log(`Loading user, ${id}`); | |
this.setState({ | |
users: {...this.state.users, [id]: {id: id}} | |
}); | |
} | |
render() { | |
return ( | |
<BrowserRouter> | |
<App | |
loadUser={this.loadUser.bind(this)} | |
state={this.state} | |
/> | |
</BrowserRouter> | |
); | |
} | |
} | |
export default AppRouter; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment