
Cryptocurrencies, especially Bitcoin, have become a significant part of the financial market. For web developers and crypto enthusiasts, integrating real-time Bitcoin price tracking into a web application can be an exciting and valuable feature. In this post, we'll walk through how to fetch the current price of Bitcoin using ReactJS and the Kraken API.
Kraken is a popular cryptocurrency exchange that offers a powerful API for accessing cryptocurrency data. Their public API doesn't require authentication, which makes it a great choice for retrieving Bitcoin's current price.
First, you'll need to have Node.js installed on your computer. Once you have Node.js, you can create a new React application by running:
npx create-react-app bitcoin-price-tracker
cd bitcoin-price-trackerWhile React does have built-in methods to fetch data, we'll use Axios for its simplicity and ease of use. Install it by running:
npm install axiosNow, let's create a simple component to display Bitcoin's current price. Create a new file called BitcoinPrice.js in your src folder.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const BitcoinPrice = () => {
const [price, setPrice] = useState(null);
useEffect(() => {
const fetchPrice = async () => {
try {
const response = await axios.get('https://api.kraken.com/0/public/Ticker?pair=XBTUSD');
setPrice(response.data.result.XXBTZUSD.c[0]);
} catch (error) {
console.error('Error fetching data: ', error);
}
};
fetchPrice();
}, []);
return (
<div>
<h1>Current Bitcoin Price</h1>
<p>{price ? `$${price}` : 'Loading...'}</p>
</div>
);
};
export default BitcoinPrice;In this component, we use useState to store the price and useEffect to fetch the price when the component mounts. The Axios get method is used to make a request to the Kraken API endpoint for the Bitcoin to USD ticker information.
Finally, let’s display our BitcoinPrice component. Update the App.js to include our new component.
import React from 'react';
import './App.css';
import BitcoinPrice from './BitcoinPrice';
function App() {
return (
<div className="App">
<header className="App-header">
<BitcoinPrice />
</header>
</div>
);
}
export default App;Run your application:
npm startThis simple application demonstrates how you can use ReactJS and Axios to fetch and display real-time data from an API. By integrating the Kraken API, you can expand this application to include prices of other cryptocurrencies, historical data analysis, and much more.
Remember to always handle API responses and errors gracefully in a production application to ensure a robust and user-friendly experience. Happy coding!
Thank you for reading this far! Let’s connect. You can @ me on X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.