|
// This project derived from: |
|
// https://laracasts.com/series/do-you-react/episodes/7 |
|
// Laracasts: [Do You React?] |
|
// --- --- --- --- --- --- --- --- --- |
|
|
|
// HTML CODE |
|
|
|
// <div id="container"> |
|
|
|
// JS CODE |
|
|
|
// GistBox |
|
// GistForm |
|
// GistList |
|
// Gist |
|
|
|
console.clear() |
|
|
|
class GistBox extends React.Component { |
|
constructor(props) { |
|
super(props) |
|
this.state = { |
|
gistList: [] |
|
} |
|
this.submitUsername = this.submitUsername.bind(this) |
|
this.updateGistList = this.updateGistList.bind(this) |
|
} |
|
submitUsername(username) { |
|
const url = `https://api.github.com/users/${username}/gists` |
|
|
|
fetch(url, { |
|
method: 'GET' |
|
}).then( response => |
|
response.json() |
|
).then( data => { |
|
if (data.length > 0) { |
|
this.updateGistList(data[0]) |
|
} else { |
|
alert('User has no gists') |
|
} |
|
}) |
|
} |
|
updateGistList(gist) { |
|
const username = gist.owner.login, |
|
url = gist.html_url, |
|
gistList = this.state.gistList.concat({username, url}) |
|
this.setState({ gistList }) |
|
} |
|
render() { |
|
return ( |
|
<div> |
|
<GistForm onAdd={this.submitUsername} /> |
|
<GistList gistList={this.state.gistList} /> |
|
{this.props.children} |
|
</div> |
|
) |
|
} |
|
} |
|
class GistForm extends React.Component { |
|
constructor(props) { |
|
super(props) |
|
this.state = { |
|
potentialGist: '' |
|
} |
|
this.gistInMotion = this.gistInMotion.bind(this) |
|
this.getNewGist = this.getNewGist.bind(this) |
|
} |
|
gistInMotion(e) { |
|
this.setState({ |
|
potentialGist: e.target.value |
|
}) |
|
} |
|
getNewGist(e) { |
|
e.preventDefault() |
|
this.props.onAdd(this.state.potentialGist) |
|
this.setState({gist: ''}) |
|
} |
|
render() { |
|
return ( |
|
<div> |
|
<form onSubmit={this.getNewGist}> |
|
<label>Enter a GitHub username for a link to their last Gist:<br/> |
|
<input type="text" onChange={this.gistInMotion} value={this.state.potentialGist} /> |
|
</label> |
|
<button>Get Gist</button> |
|
</form> |
|
</div> |
|
) |
|
} |
|
} |
|
class GistList extends React.Component { |
|
constructor(props) { |
|
super(props) |
|
} |
|
render() { |
|
return ( |
|
<div> |
|
{ this.props.gistList.map( (gist, idx) => <Gist key={idx} gist={gist} /> )} |
|
</div> |
|
) |
|
} |
|
} |
|
class Gist extends React.Component { |
|
constructor(props) { |
|
super(props) |
|
} |
|
render() { |
|
return ( |
|
<div className="listitem"> |
|
{this.props.gist.username} - <a href={this.props.gist.url} target="_blank">{this.props.gist.url}</a> |
|
</div> |
|
) |
|
} |
|
} |
|
ReactDOM.render( |
|
<GistBox />, |
|
container |
|
) |