Create Cool Plots With React and Plotly
Tags: javascript, webdev, react, tutorial
Published: 2022-02-12 10:39:03

Today I will show you how to create an interactive plot with React and Plotly library that you can use in your React web apps!
Let's start cooking!🍳

**Step 1**
In this tutorial we will plot 24hr price change of cryptocurrency. To do that we will need an API to get data. I will use [Alpha Vantage](https://www.alphavantage.co/documentation/) API to fetch data. You can grab your own API key on their website or just use demo key.

To get data from API we will use `fetchData` function:

```javascript
const fecthData = async () => {
  const apiKey = "demo";
  const url = `https://www.alphavantage.co/query?function=CRYPTO_INTRADAY&symbol=ETH&market=USD&interval=5min&apikey=${apiKey}`;
  return fetch(url)
    .then((res) => {
      if (res.status === 200) {
        return res.json();
      }
    })
    .then((data) => {
      return data["Time Series Crypto (5min)"];
    });
};
```
This function is asynchronous because it takes time to retrieve data and we don't want our application to be blocked during this time!

**Step 2**
Then we need to install Plotly. To do this just run the following command in your terminal:
`npm install react-plotly.js plotly.js`
After installation import Plotly and React hooks that we will need for state management:

```javascript
import Plot from "react-plotly.js";
import { useState, useEffect } from "react";
```

**Step 3**
We will create functional React component for our app:

```javascript
export default function App() {
  const [data, setData] = useState([]);
  const [dataIsLoaded, setDataIsLoaded] = useState(false);
if (dataIsLoaded) {
    return <div>Loaded</div>;
 } else {
    return <div>Loading...</div>;
  }
```
We will show our plot only after our data is loaded. To do this we will use Boolean variable `dataIsLoaded` that will be set to true when we get data. Variable `data` will be used to store retrieved data.

**Step 4**
We want to fetch data only once when the app is loaded. To make this happen we will use React `useEffect` hook, everything we write inside this hook will be executed only once:

```javascript
useEffect(() => {
    fecthData().then((res) => {
      setData(res);
      setDataIsLoaded(true);
    });
  }, []);
```
We use `.then` with our `fetchData()` because it returns Promise and after this Promise will be returned we will set our data variable to the response from the API. After that we will set `dataIsLoaded` to true to render our plot.

**Step 5**
To be able to show our plot we need `x` and `y` variables: `x` for x axis and `y` for y axis:

```javascript
const X = Object.keys(data);
const Y = X.map((date) => {
    return data[date]["1. open"];
  });
```
On x axis we will show the date and on the y axis we will show the open price of ETH.

**Step 6**
To create a line chart we will use `Plot` component with type `scatter` and mode `lines`. Also we will set some layout options to add title, change range of y axis, background color and font:

```javascript
if (dataIsLoaded) {
    return (
      <Plot
        data={[
          {
            x: X,
            y: Y,
            fill: "tonexty",
            type: "scatter",
            marker: { color: "#8000DE" }
          }
        ]}
        layout={{
          width: 500,
          height: 300,
          title: "ETH-USD",
          yaxis: {
            range: [2850, 3000],
            type: "linear"
          },
          paper_bgcolor: "rgb(243, 243, 243)",
          plot_bgcolor: "#f3f3f3",
          family: "Courier New, monospace"
        }}
      />
    );
  }
```
You should get something like this:
![ETH plot line](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eysgmdvln8kapq60zfx0.png)
And to add fill under plot just use `fill` property in data:

```javascript
data={[
          {
            x: X,
            y: Y,
            fill: "tonexty", // add this
            type: "scatter",
            mode: "lines",
            marker: { color: "#8000DE" }
          }
        ]}
```
You can learn more about different plot types and their attributes on the official [Plotly](https://plotly.com/javascript/) website.
Also you can view all the source code and live demo on my [CodeSandBox](https://codesandbox.io/s/react-plot-demo-t0u9j?file=/src/App.js).

That's all!😃
Hope you liked this tutorial and happy coding!