Skip to content

Instantly share code, notes, and snippets.

@jackyef
Last active July 14, 2018 15:41
Show Gist options
  • Save jackyef/5fa8dc9139782bcab6c0ef36ca77bfd3 to your computer and use it in GitHub Desktop.
Save jackyef/5fa8dc9139782bcab6c0ef36ca77bfd3 to your computer and use it in GitHub Desktop.
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