In this tutorial, we will be using React to build a live cryptocurrency ticker to display information about Bitcoins, Ethereum and Litecoins.

The React logo.

React ⚛️ is a JavaScript library for building user interfaces from Facebook, serving as its answer to Google's popular Angular framework. With React, you can create an interactive and modular front-end with components that are reusable while performing well by only making changes to the DOM when needed. React is extremely popular and this tutorial will help you get started with it.

With cryptocurrency taking the world by storm, creating a cryptocurrency ticker app is the perfect way to use many different React features to build a functioning finished product that is actually usable.

Here's a look at the React app we will build:

By the time you see this tutorial, these prices will be wildly outdated! #JustCryptocurrencyThings

You can view live demo for this app before continuing with this tutorial.

Basic HTML knowledge is needed. If you're absolutely new, check out our class on HTML. Intermediate JavaScript knowledge is also needed. If you need a refresher, check out our class on JavaScript.

Being familiar with CSS is completely optional as the styles will be provided, but it helps.

To install and run our React app, we will first need Node.js, a JavaScript runtime.

Visit the official Node.js website to get the installer. After it downloads, run the installer until the end. Restart your computer to ensure the changes can take effect.

The Node.js installer.

The Node.js installer should have also installed NPM for you. To confirm that you have installed both properly, you'll need to open Windows Command Prompt if you're on Windows, or Terminal if you're on Mac or Linux.

To check if you installed node:

node -v

To check if you installed NPM:

npm -v

If both of these commands return a version number, you're good to go.

Realizing just how difficult it is for newcomers to get into React, Facebook created an NPM module called Create React App to simplify set up. This tool preconfigures your environment so that you can jump right into coding. It's the fastest way to get to React's version of a "Hello World".

Install it globally:

npm install -g create-react-app

Now use it to create your React app:

create-react-app cryptocurrency-ticker-app

After that finishes doing what it needs to do, you will now have a basic React app ready to be worked on.

This is how your project should look like now:

The project's folder structure.

Curious about what these folders and files are for?

node_modules : All the packages that are installed that your app uses.

: All the packages that are installed that your app uses. public : All the files you can access directly from your browser like static assets.

: All the files you can access directly from your browser like static assets. src : The source files for your React app.

: The source files for your React app. .gitignore : The file that tells git what to ignore.

: The file that tells git what to ignore. package.json : A file that contains various information about your React app.

: A file that contains various information about your React app. README.md : A file written in markdown that has important information.

Feel free to start it up by entering these two commands:

cd cryptocurrency-ticker-app

npm start

This will enter the folder that the app resides in, and then start the development server on port 3000 by default. If done properly, you should see this in your browser when you head to:

http://localhost:3000/

Basic Create React App set up.

If you make any code changes, it should automatically reload them in your browser for you thanks to the built-in file watcher that watches for your changes.

As mentioned before, the way to build user interfaces in React revolves around the idea of breaking that interface up into smaller chunks called components. Components can then be independently worked on and be reused as many times as we want.

If you open index.js , you'll see a bunch of imports at the top, but then we get to:

ReactDOM.render(<App />, document.getElementById('root'));

This line of code is saying "hey, get me the App component, and render it at the element with id root ". If you're interested where that is, if you open index.html , you'll see:

<div id="root"></div>

That is where React renders the entire app. Open App.js , where the App component lives, and you'll see the entire component:

class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } }

Because this component is simple, it is only defining the render() function which returns the markup to render. Technically, what you're seeing is actually called JSX, but you don't need to worry if you've never heard of that term before. You can think of it as just HTML that allows you to add in some JavaScript.

For now, just replace the contents of your App.js with this:

import React, { Component } from 'react'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <h2>Cryptocurrency Ticker</h2> </div> </div> ); } } export default App;

This gets rid of everything we don't need like React's logo. Likewise, we don't need a lot of the styles inside App.css and so you can replace it with this:

.App { text-align: center; } .App-header { background-color: #222; color: white; font-size: 1.25rem; margin: 0; padding: 1rem; }

Once that is done, save the changes, and if you still have your development server running, you should see this:

Our blank slate React app.

For our cryptocurrency ticker app, we can divide up the user interface into two parts, the individual cryptocurrencies using one component, and then a parent component which handles the data for all of them. Let's start with the parent component, and call it Tickers .

Create a folder called components inside src , and inside that create two files, Tickers.js and Tickers.css .

Place this inside your Tickers.css file:

.tickers { list-style-type: none; padding: 0; display: inline-flex; }

Now inside Tickers.js , let's start off with a basic React component:

import React, { Component } from 'react'; import './Tickers.css'; class Tickers extends Component { constructor(props) { super(props); this.state = { data: [ { id: "bitcoin", price: "1" }, { id: "ethereum", price: "1" }, { id: "litecoin", price: "1" } ] }; } render() { var tickers = this.state.data.map((currency) => <li key={currency.id}> <h3>{currency.id}</h3> <h4>{currency.price} USD</h4> </li> ); return ( <div className="tickers-container"> <ul className="tickers">{tickers}</ul> <p>Information updated every minute courtesy of coinmarketcap.com</p> </div> ); } } export default Tickers;

Let's break down what's going on.

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

This simply imports React and Component from react so that we can use them. Then we import our CSS file so the styles are applied.

constructor(props) { super(props); this.state = { data: [ { id: "bitcoin", price: "1" }, { id: "ethereum", price: "1" }, { id: "litecoin", price: "1" } ] }; }

The constructor function is what is called when a component is created. It is used to construct the component. Properties can be passed into any component, and that's what props is for, but since we aren't dealing with them here, they're not important to know as of now.

Components in React can have state, basically data that a component can keep track of to function properly. We do this by setting the state on this.state . In our case, we are listing our three cryptocurrencies and giving them a price of 1 USD each. Later in this tutorial we will hook this up to real data.

render() { var tickers = this.state.data.map((currency) => <li key={currency.id}> <h3>{currency.id}</h3> <h4>{currency.price} USD</h4> </li> ); return ( <div className="tickers-container"> <ul className="tickers">{tickers}</ul> <p>Information updated every minute courtesy of coinmarketcap.com</p> </div> ); }

The key property is needed for React to keep track of each li !

As mentioned before, the render() function returns JSX (basically the HTML) needed to render the component.

The tickers variable contains all the list items ( li 's), one for each cryptocurrency. We are using the map function for arrays to iterate through each cryptocurrency, creating li elements, and then simply outputting both the cryptocurrency's id and the price for it.

Lastly, we are returning a div containing our ul with tickers passed in, and a simple p tag crediting the source for the real information, coinmarketcap.com.

Now that our component is ready, we need to call it inside App.js . Open the file up and import the component by placing this at the top:

import Tickers from './components/Tickers.js';

And include the Tickers component in the render function:

render() { return ( <div className="App"> <div className="App-header"> <h2>Cryptocurrency Ticker</h2> </div> <Tickers /> </div> ); }

If done correctly, you should now see this (ignore the styling for now):

Our app with fake data.

Our app is now ready for a child component to handle each indiviudal cryptocurrency. This will make it easier to add new features and styles that will be reflected across all three cryptocurrencies.

Inside the components folder, create two more files, Cryptocurrency.css and Cryptocurrency.js . Again, for simplicity's sake, place this inside your Cryptocurrency.css :

.cryptocurrency { padding: 1rem 2rem 2rem; margin: 1rem; border-radius: 0.5rem; min-width: 9rem; border: solid 1px rgba(0, 0, 0, 0.05); } .cryptocurrency p { color: rgba(0, 0, 0, 0.75); } .cryptocurrency-name { font-size: 1.25rem; } .bitcoin { background-color: #fbe2c3; border-bottom: solid 4px #f7931a; } .ethereum { background-color: #c2c9ff; border-bottom: solid 4px #454a75; } .litecoin { background-color: #ececec; border-bottom: solid 4px #bebebe; }

Luckily for us, Cryptocurrency.js is a fairly simple component:

import React, { Component } from 'react'; import './Cryptocurrency.css'; class Cryptocurrency extends Component { render() { var { id, name, symbol, price_usd, percent_change_1h, percent_change_24h, percent_change_7d, } = this.props.data; return ( <li className={"cryptocurrency " + id}> <p className="cryptocurrency-name">{name} ({symbol})</p> <h1>${ (+price_usd).toFixed(2) }</h1> <p>{percent_change_1h}% 1hr</p> <p>{percent_change_24h}% 24hrs</p> <p>{percent_change_7d}% 7days</p> </li> ); } } export default Cryptocurrency;

Seems wild at first, but let's break this down.

var { id, name, symbol, price_usd, percent_change_1h, percent_change_24h, percent_change_7d, } = this.props.data;

This is using a technique called object destructuring to assign 7 new variables the values inside this.props.data . For example, if this.props.data.price_usd was equal to 100 , then the value of the price_usd variable would also be equal to 100 .

data

return ( <li className={"cryptocurrency " + id}> <p className="cryptocurrency-name">{name} ({symbol})</p> <h1>${(+price_usd).toFixed(2)}</h1> <p>{percent_change_1h}% 1hr</p> <p>{percent_change_24h}% 24hrs</p> <p>{percent_change_7d}% 7days</p> </li> );

is just a property containing all of the data needed for a single cryptocurrency, which we will eventually pass in from the parent component.

This JSX is the markup to be returned representing a single cryptocurrency. It includes the name, symbol, price to the nearest 2 decimal places, and how much the cryptocurrency changed in value over the past hour, 24 hours, and 7 days.

All great information to know if you're interested in the state of the cryptocurrency at a glance!

Swing back to your Tickers.js file so we can make the two changes needed to use this new child component.

First, replace our state with the new structure we need:

this.state = { data: [ { id: "bitcoin", name: "Bitcoin", symbol: "BTC", price_usd: "1", percent_change_1h: "0", percent_change_24h: "0", percent_change_7d: "0", }, { id: "ethereum", name: "Ethereum", symbol: "ETH", price_usd: "1", percent_change_1h: "0", percent_change_24h: "0", percent_change_7d: "0", }, { id: "litecoin", name: "Litecoin", symbol: "LTC", price_usd: "1", percent_change_1h: "0", percent_change_24h: "0", percent_change_7d: "0", } ] };

Now that the data can be used, we need to pass it in to our new Cryptocurrency component. Import the Cryptocurrency component inside Tickers.js :

import Cryptocurrency from './Cryptocurrency';

and then replace the initialization of tickers with this:

var tickers = this.state.data.map((currency) => <Cryptocurrency data={currency} key={currency.id} /> );

Now that's some beautiful code. 😍

This iterates through the this.state.data array and create a new Cryptocurrency component for every element. It then passes in all the data in as a property called data . This is how the child component is able to access this information by using this.props.data .

Our app with the updated user interface.

With dummy data working and the user interface looking great, the very last piece of this app is loading the real data so that this becomes actually functional. As mentioned before, we will be getting our data from coinmarketcap.com, so thanks to them for their service.

To get this data from them, we will be using Axios to interact with their API. Before we do that, we must first install it.

Install it by running this command:

npm install axios --save

After that's successful, import it inside Tickers.js which is where we'll need to use it:

import axios from 'axios';

With that installed, we can proceed to use it to fetch some delicious data. Let's add a method that fetches cryptocurrency data:

fetchCryptocurrencyData() { axios.get("https://api.coinmarketcap.com/v1/ticker/?limit=10") .then(response => { var wanted = ["bitcoin", "ethereum", "litecoin"]; var result = response.data.filter(currency => wanted.includes(currency.id)); this.setState({ data: result}); }) .catch(err => console.log(err)); }

Simply put, fetchCryptocurrencyData() uses Axios to make a GET request to their API, then we filter out only the cryptocurrencies we want (because coinmarketcap.com returns some we don't want) by ensuring only cryptocurrencies that are included in the wanted array are selected, and then we set the state of our component with the results of the filtering to the data property.

Recall that this.state.data is the same piece of information that our child component Cryptocurrency uses to render itself, meaning once we change the state, React will automatically reflect those changes.

Now all we need to do is not only call fetchCryptocurrencyData() right at the beginning, but to continously call it every minute so that our app maintains fresh data.

React offers us a way to execute code right when a component is in view with the componentDidMount() function, so we'll define one inside of Tickers.js :

componentDidMount() { this.fetchCryptocurrencyData(); this.interval = setInterval(() => this.fetchCryptocurrencyData(), 60 * 1000); }

First we call fetchCryptocurrencyData() to get the data right away, then we set an interval to repeat every minute that once again calls fetchCryptocurrencyData() to get the latest data.

Your finalized Tickers.js should look something like this:

import React, { Component } from 'react'; import axios from 'axios'; import './Tickers.css'; import Cryptocurrency from './Cryptocurrency'; class Tickers extends Component { constructor(props) { super(props); this.state = { data: [ { id: "bitcoin", name: "Bitcoin", symbol: "BTC", price_usd: "1", percent_change_1h: "0", percent_change_24h: "0", percent_change_7d: "0", }, { id: "ethereum", name: "Ethereum", symbol: "ETH", price_usd: "1", percent_change_1h: "0", percent_change_24h: "0", percent_change_7d: "0", }, { id: "litecoin", name: "Litecoin", symbol: "LTC", price_usd: "1", percent_change_1h: "0", percent_change_24h: "0", percent_change_7d: "0", } ] }; } componentDidMount() { this.fetchCryptocurrencyData(); this.interval = setInterval(() => this.fetchCryptocurrencyData(), 60 * 1000); } fetchCryptocurrencyData() { axios.get("https://api.coinmarketcap.com/v1/ticker/") .then(response => { var wanted = ["bitcoin", "ethereum", "litecoin"]; var result = response.data.filter(currency => wanted.includes(currency.id)); this.setState({ data: result}); }) .catch(err => console.log(err)); } render() { var tickers = this.state.data.map((currency) => <Cryptocurrency data={currency} key={currency.id} /> ); return ( <div className="tickers-container"> <ul className="tickers">{tickers}</ul> <p>Information updated every minute courtesy of coinmarketcap.com</p> </div> ); } } export default Tickers;

At last, we can now save all our files, and look at the browser to see the finished working app:

Finished cryptocurrency ticker app.

The app will remain real-time so there's no need to refresh the page. Adding new cryptocurrencies to this app is as easy as adding more elements to the wanted array where we filter out those that don't match.

Again, feel free to check out the live demo for this app!

Hopefully this tutorial has helped you get started on one of the hottest technologies right now. If you have any questions, definitely leave a comment below or contact us through any of our social media accounts!

Interested in investing in Cryptocurrency?

Cryptocurrency is still a young technology with a near limitless potential. If you're interested in investing, we highly recommend Coinbase as they make it very easy for newcomers to begin their adventure. Once signed up, you can then purchase, sell, and transfer Bitcoin, Ethereum, Bitcoin Cash, and Litecoin.

If you're feeling adventurous, you can invest in other coins not listed on Coinbase by signing up for another exchange we also highly recommend called Binance. After you have tranferred some of the cryptocurrency you purchased on Coinbase to Binance, you can then go on to buy a lot of different coins, each with its own purpose for existing.

Good luck and thanks for reading!

If you learned from this tutorial, please consider supporting us! Follow us on Facebook, Twitter and LinkedIn! 😊 Also, join the conversation over at our official forum!