Skip to content

Instantly share code, notes, and snippets.

@juhahinkula
Last active February 13, 2018 13:02
Show Gist options
  • Save juhahinkula/c2570807ee36696c6423d4966614be3b to your computer and use it in GitHub Desktop.
Save juhahinkula/c2570807ee36696c6423d4966614be3b to your computer and use it in GitHub Desktop.
NASA APOD API usage with React
<!-- Fetch astronomy picture of the day from NASA API -->
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>React getting started</title>
</head>
<body>
<!-- Root container for react components -->
<div id='root'></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/babel">
class RestNasa extends React.Component {
constructor(props) {
super(props);
this.state = {explanation: '', imgurl: ''};
}
componentDidMount() {
fetch('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
this.setState({
explanation: responseData.explanation,
imgurl: responseData.url
});
});
}
render() {
return (
<div>
<div>Explanation: {this.state.explanation}</div>
<div>
<img src={this.state.imgurl} />
</div>
</div>
);
}
}
ReactDOM.render(<RestNasa />, document.getElementById('root'));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment