Created
October 20, 2017 15:32
-
-
Save dceddia/8adcfb3e037b41c6e6335ce49cec870a to your computer and use it in GitHub Desktop.
Fetching users from Express, while also using React Router
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, { Component } from 'react'; | |
import { | |
BrowserRouter as Router, | |
Route, | |
Link | |
} from 'react-router-dom'; | |
import './App.css'; | |
class UsersView extends Component { | |
state = {users: []} | |
componentDidMount() { | |
fetch('/users') | |
.then(res => res.json()) | |
.then(users => this.setState({ users })); | |
} | |
render() { | |
return ( | |
<div> | |
<h1>Users</h1> | |
{this.state.users.map(user => | |
<div key={user.id}>{user.username}</div> | |
)} | |
</div> | |
); | |
} | |
} | |
const Home = () => ( | |
<div> | |
<h2>Home</h2> | |
</div> | |
) | |
class App extends Component { | |
render() { | |
return ( | |
<div className="App"> | |
<Router> | |
<div> | |
<ul> | |
<li><Link to="/">Home</Link></li> | |
<li><Link to="/show-users">Users</Link></li> | |
</ul> | |
<Route exact path="/" component={Home}/> | |
<Route path="/show-users" component={UsersView}/> | |
</div> | |
</Router> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment