Let's start with the basic app is the react to display Cryptocurrency of the day.
In this blog, you will learn following
- How to create a react app from scratch
- How to use useState Hook
- How to use useEffect Hook
- Calling an API using Axios
Creating App in react
Create React App is a comfortable environment for learning React and is the best way to start building a new single-page application in React.
npx create-react-app crypto-tracker
cd crypto-tracker
npm start
(To execute the above commands Node.JS must be installed on your system you can use the following link to install Node.JS
https://nodejs.org/en/download/
crypto-tracker is app name.
You can open crypto-tracker in the Visual Studio Code so that you can start developing your react app.
You will see the following structure of your application
You will see app.js file
Installing Axios (Promise based HTTP client for the browser and node.js)
$ npm install axios
Using Axios
To use axios first we need to import axios
import axios from 'axios';
We will get CryptoCurrency for the day data from REST API.
*Let's create API folder in the src folder and add CryptoAPI.js *
Add following code in CryptoAPI.js
CryptoAPI.js
import React, { Component } from 'react';
import axios from 'axios';
export default class CryptoAPI extends React.Component {
static getCoinOfTheDay() {
return new Promise((resolve, reject) => {
const url =
'https://api.lunarcrush.com/v2?data=coinoftheday&key=XXXXXXXXXXXXXXXXX';
axios
.get(`${url}`)
.then(res => {
resolve(res.data.data);
})
.catch(err => reject(err));
});
}
}
Now we have successfully implemented code to call API using Axios.
It's time to create a component that will display the Currency Name and its symbol.
Add Presentation folder in the src folder and add CoinOfTheDay.js
CoinOfTheDay.js
import React from 'react';
function CoinOfTheDay(props) {
return (
<div>
{props.data && (
<div>
<span> Coin of the Day</span> <br />
<span> Name : {props.data.name} </span> <br />
<span> Symbol : {props.data.symbol} </span>
</div>
)}
</div>
);
}
export default CoinOfTheDay;
We will pass data to CoinOfTheDay.js to display.
Adding CoinOfTheDay in the App.js and Passing data from API call
import { useState, useEffect } from 'react';
import './App.css';
import CryptoAPI from './Api/CryptoAPI';
import CoinOfTheDay from './Presentation/CoinOfTheDay';
function App() {
const [coinOfTheDay, getCoinOfTheDay] = useState('');
useEffect(() => {
CryptoAPI.getCoinOfTheDay().then(res => {
getCoinOfTheDay(res);
});
}, []);
return (
<div className='App'>
<header className='App-header'>
<h1>React Crypto Chart</h1>
<CoinOfTheDay data={coinOfTheDay}></CoinOfTheDay>
</header>
</div>
);
}
export default App;
Run your application using the following command.
npm start
You will see the Cryptocurrency coin of the day
We will continue to extend this application to display Graphical Charts related to Cryptocurrencies and related information.
Your suggestions are always welcome.
Top comments (0)