</> Michael Burrows

Build a React component to display the Bitcoin price from an API

Last modified on September 30th 2020 GitHub [Source] CodePen [Demo]

Learn how to build a React component that fetches the current Bitcoin price from an API.

Bitcoin Price React Component

To complete this tutorial we’ll be working with the following files:

├ BitcoinPrice.js ├ BitcoinPrice.css ├ bitcoin-logo.png

You can download a free Bitcoin logo to use from icons8.com.

Let’s start by setting up the imports in our BitcoinPrice.js file:

import React, { Component } from "react"; import logo from './bitcoin-logo.png'; import "./BitcoinPrice.css";

After the imports we’ll create a React class based component with the following methods:

class BitcoinPrice extends Component { constructor() { // STEP 1 } componentDidMount() { // STEP 2 } render() { // STEP 3 } } export default BitcoinPrice;

STEP 1

Inside the constructor() we’ll define the default state for “loading” and “price”:

super(); this.state = { loading: false, price: {} };

STEP 2

Inside componentDidMount() we’ll being using the vanilla JavaScript fetch() method.

The API used here (https://blockchain.info/ticker) is free and no access token is required:

this.setState({ loading: true }); fetch("https://blockchain.info/ticker") .then((response) => { if (response.ok) { return response.json(); } else { throw new Error("NETWORK RESPONSE ERROR"); } }) .then((data) => { console.log(data); this.setState({ price: data.USD, loading: false, }) }) .catch((error) => this.setState({ error, loading: false }));

If the fetch() was successful you should see the following in the browser console:

Bitcoin API data

The data contains the Bitcoin price for a number of different currencies, in this example we’ll be using USD.

STEP 3

Inside the render() method add the following:

const { loading , price } = this.state; const output = loading ? "LOADING..." : "$"+price.last; return ( <div className="btc"> <img className="btc-logo" src={logo} alt="Bitcoin" /> <span className="btc-price">{output}</span> </div> );

const output checks if loading is true and displays “LOADING…”, otherwise it’ll display the Bitcoin price.

To complete the component add the following CSS to the BitcoinPrice.css file:

.btc { background-color: darkcyan; display: flex; justify-content: center; align-items: center; height: 60px; } .btc-logo { height: 25px; margin-right: 5px; } .btc-price { color: #fff; font-size: 18px; font-weight: bold; font-family: sans-serif; }

Thanks for reading, and I really hope you enjoyed this tutorial.