Last active
July 14, 2018 15:41
-
-
Save jackyef/5fa8dc9139782bcab6c0ef36ca77bfd3 to your computer and use it in GitHub Desktop.
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, Fragment } from 'react'; | |
import { number } from 'prop-types'; | |
class Comic extends Component { | |
static baseComicUrl = `https://xkcd.now.sh/:comicId`; | |
static propTypes = { | |
id: number.isRequired, | |
}; | |
state = { | |
loading: true, | |
error: false, | |
}; | |
componentDidMount() { | |
const { id } = this.props; | |
const url = Comic.baseComicUrl.replace(':comicId', id); | |
fetch(url) | |
.then(res => res.json()) | |
.then(json => this.setState({ ...json, loading: false, error: false })) | |
.catch(err => this.setState({ loading: false, error: false, errorMessage: err })); | |
} | |
renderContent() { | |
const { id } = this.props; | |
const { alt, error, img, loading, title } = this.state; | |
if (error) { | |
return <p>an error happened while trying to fetch comic #{id}</p>; | |
} | |
if (loading) { | |
return <p>loading...</p>; | |
} | |
return ( | |
<Fragment> | |
<h3>{title}</h3> | |
<figure> | |
<a href={img} target="_blank" rel="noreferrer nofollow noopener"><img src={img} /></a> | |
<figcaption>{alt}</figcaption> | |
</figure> | |
</Fragment> | |
) | |
} | |
render() { | |
return ( | |
<div> | |
{this.renderContent()} | |
</div> | |
) | |
} | |
} | |
export default Comic; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment