DEV Community

Julian Gaston
Julian Gaston

Posted on • Updated on

A Guide To Using Nivo with ReactJS

Introduction

So, you're looking to bring life to your ReactJS application with compelling data visualizations? Look no further! This guide is your ticket to exploring Nivo, a robust React library designed for creating visually stunning charts and graphs. Let's infuse your production code with the magic of data visualization.


Getting Started with Nivo and ReactJS

Start by installing Nivo into your React project. Open your terminal and run:

npm install @nivo/core @nivo/bar

Now that Nivo has been installed, let's construct a straightforward bar chart component. Open your BarChart.js file:

import React from 'react';
import { ResponsiveBar } from '@nivo/bar';

const BarChart = ({ data }) => {
  return (
    <div style={{ height: '400px' }}>
      <ResponsiveBar
        // ... (chart configuration)
      />
    </div>
  );
};

export default BarChart;
Enter fullscreen mode Exit fullscreen mode

Building a Bar Chart Component

Customize your BarChart component with your data and preferences. This simple example provides a foundation for more intricate visualizations. Below is how you would go about implementing it within your parent component.

import React from 'react';
import BarChart from './BarChart';

const App = () => {
  const data = [
    { category: 'A', value: 10 },
    { category: 'B', value: 20 },
    { category: 'C', value: 15 },
    // Add more data as needed
  ];

  return (
    <div>
      <h1>Super Cool Nivo Bar Chart</h1>
      <BarChart data={data} />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

And there you have it! You've seamlessly integrated a visually appealing bar chart into your ReactJS application using Nivo.


Nivo's Expectations for Time Series Data

Nivo requires time series data in a specific format where each row represents a timestamp and various measures associated with that timestamp. For instance, a time series line chart might expect data like:

[
  { "Timestamp": "2023-01-01T00:00:00Z", "Value": 10 },
  { "Timestamp": "2023-01-01T01:00:00Z", "Value": 20 },
  { "Timestamp": "2023-01-01T02:00:00Z", "Value": 15 }
]
Enter fullscreen mode Exit fullscreen mode

Utility Functions for Different Time Formats

Let's create utility functions to accommodate different time formats commonly encountered in APIs, such as ISO 8601 and Unix timestamps.

// Utility function to convert data into Nivo-friendly format for a line chart
const formatTimeSeriesData = (apiData, timeKey, valueKey) => {
  return apiData.map(item => ({
    [timeKey]: new Date(item.timestamp).toISOString(), // Convert to ISO 8601
    [valueKey]: item.value
  }));
};

// Utility function for APIs returning Unix timestamps
const formatUnixTimeSeriesData = (apiData, timeKey, valueKey) => {
  return apiData.map(item => ({
    [timeKey]: new Date(item.timestamp * 1000).toISOString(), // Convert to ISO 8601
    [valueKey]: item.value
  }));
};
Enter fullscreen mode Exit fullscreen mode

Example Usage with Different Time Formats

Assuming your mock API returns time series data with different time formats:

[
  { "timestamp": "2023-01-01T00:00:00Z", "value": 10 },
  { "timestamp": 1641081600, "value": 20 } // Unix timestamp
]
Enter fullscreen mode Exit fullscreen mode

You can use the utility functions as follows:

// Example usage for a line chart with ISO 8601 timestamp
const apiData = [
  { "timestamp": "2023-01-01T00:00:00Z", "value": 10 },
  { "timestamp": 1641081600, "value": 20 } // Unix timestamp
];

const nivoFormattedData = formatTimeSeriesData(apiData, "Timestamp", "Value");

console.log(nivoFormattedData);
Enter fullscreen mode Exit fullscreen mode

Bonus Tips: Making It Pop!✨

Customize your chart further with your own styles using Nivo's abundance of options:

// Example: Customizing bar colors
colors={{ scheme: 'set1' }}
Enter fullscreen mode Exit fullscreen mode

Make your chart dynamic by fetching data from an API or your server. Use state and hooks to keep your UI reactive and fresh:

import { useState, useEffect } from 'react';

const App = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch data from your API
    // Update state with the fetched data
  }, []);

  return (
    <div>
      <h1>Dynamic Nivo Bar Chart</h1>
      <BarChart data={data} />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Side Note

If you don't have a readily available API for your needs you can use DummyJSON. This provides a free API to use that returns dummy data. I have used it before in side projects and can say its great for generating dummy data.


Conclusion

With Nivo and ReactJS, the world of data visualization is at your fingertips. Experiment, customize, and turn your data into a visual masterpiece that captivates your users. Happy charting! πŸ“Šβœ¨

Top comments (1)

Collapse
 
milkty profile image
Tyler

WOW Talk about an informative post! This is the most amazing guide I have ever read.