Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

React CryptoCurrency Tutorial - Display Exchange Data with an API

By Gary simon - Sep 26, 2017

Being that React is perhaps the most popular modern frontend javascript framework, then it makes complete sense to start using it to develop for the growing CryptoCurrency industry. In this tutorial, you're going to learn how to use React to connect to a 100% free, public cryptocurrency API called CryptoCompare.

Also, I have covered this same exact process for the other 2 popular javascript frameworks (Angular and Vue.js):

Let's get started.

If you prefer watching a video tutorial instead..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more awesome videos.

Prerequisites

React requires Node.js with NPM (Node Package Manager). To check whether or not you have it, go to your command line or console and type:

> node -v
> npm -v

If either of these commands are unrecognized, visit Nodejs.org and download the appropriate installer based on your OS. Install it with the default settings and reload your command line; you're set.

Installing the React CLI & Starting the Project

The React CLI (Command Line Interface) allows you to quickly and easily create a React project. First, we need to use NPM to install it:

> npm install create-react-app -g

Once finished, we'll use the CLI to start a new React project:

> create-react-app react-crypto

This will start a new React app with the project and folder name being react-crypto.

Next:

> cd react-crypto
> yarn start              (or npm start)

If you have yarn, you can use yarn start or npm start to launch a local development server with the React project ready to go in the browser.

Connecting to the CryptoCompare API

Next, we need to install the HTTP client library Axios. This will allow us to make a get call to the desired endpoint to fetch the cryptocurrency information.

In the console, type:

> npm install axios --save

Open up your code editor (I use Visual Studio Code), and navigate to /src/App.js which is where we'll work for the remainder of this tutorial.

At the top of this file, we need to import axios:

import React, { Component } from 'react';
import './App.css';
import axios from 'axios';

We need to add a constructor to pass in our props(or properties). So, just inside of our class as shown below, we add:

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      cryptos: []
    };
  }

  // Other code removed for brevity

Notice we have defined a cryptos property. This will hold the response data from the API.

Next, we use componentDidMount() function to call axios.get:

class App extends Component {

  constructor(props) { ... }

  componentDidMount() {
    axios.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,IOT&tsyms=USD')
      .then(res => {
        const cryptos = res.data;
        console.log(cryptos);
        this.setState({cryptos: cryptos});
      })
  }

 The URL as shown in the first argument of axios.get is one of many different endpoints that you can use based on the CryptoCompare API documentation. Now would be a good time to view this document and discover the various cryptocurrency data you can retrieve for your app. 

In our instance, we're simply using pricemulti for Bitcoin, Ethereum and IOTA. Then, we're requesting the USD (US Dollar) value equivalent for each of the specified currencies.

We're using console.log to show the full response of the request, which is useful when constructing the template view.

Defining the Template

Inside of the render() section of the component, we need to take our cryptos property, which is essentially an object of objects, and iterate through them.

Change the render return HTML to look like this:

  render() {
    return (
      <div className="App">
        {Object.keys(this.state.cryptos).map((key) => (
          <div id="crypto-container">
            <span className="left">{key}</span>
            <span className="right">{this.state.cryptos[key].USD}</span>
          </div>
        ))}
      </div>
    )
  }

We're using Object.keys which gives us access to the object keys, along with .map to iterate over the object.

The {key} displays the cryptocurrency acronym (BTC, ETH, IOT, etc..) and we use the key on our cryptos object, along with .USD to display the dollar amount.

Open up the /src/App.css file to apply some really quick rulesets:

body {
  background: #f1f1f1;
  padding:50px;
}

div#crypto-container {
  background:white;
  width: 70%;
  margin: 0 auto 4px auto;
  padding: 1em;
  box-shadow: 1px 1px 0 lightgrey;
}

span.left {
  font-weight: bold;
}

span.right {
  float:right;
}

Proper Number Formatting

Notice how ugly the number formatting is for the USD value amounts.

BTC: 4101.65  (It should be: $4,102.57)

Let's fix that.

Go to your console in the project folder and use npm to install a number formatting package:

> npm install react-number-format --save

Import it at the top of /src/App.js:

import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
var NumberFormat = require('react-number-format');

Next, replace the contents of <span class="right">...</span> to:

<NumberFormat value={this.state.cryptos[key].USD} displayType={'text'} decimalPrecision={2} thousandSeparator={true} prefix={'$'} />

This will give you properly formatted USD amounts.

Conclusion

Hopefully, this short tutorial helped give you a quick jumpstart into the world of React development and cryptocurrency.

Enjoy!


Share this post




Say something about this awesome post!