Integrating Nivo Line Charts into Your React Application
Written on
Adding Charts to Our React Application with Nivo
In this guide, we will explore how to effectively integrate line charts into our React application using Nivo. This powerful library simplifies the process of adding visually appealing charts for data representation.
To get started, we must install the necessary packages. You can do this by executing the following command:
npm install @nivo/line
Once the installation is complete, we can proceed to include the line chart in our application. The following code snippet demonstrates how to do this:
import React from "react";
import { ResponsiveLine } from "@nivo/line";
const data = [
{
id: "japan",
color: "hsl(70, 70%, 50%)",
data: [
{ x: "plane", y: 140 },
{ x: "helicopter", y: 80 },
{ x: "boat", y: 134 },
{ x: "train", y: 202 },
{ x: "subway", y: 143 },
{ x: "bus", y: 266 },
{ x: "car", y: 223 },
{ x: "moto", y: 100 }
]
},
{
id: "france",
color: "hsl(89, 70%, 50%)",
data: [
{ x: "plane", y: 267 },
{ x: "helicopter", y: 192 },
{ x: "boat", y: 259 },
{ x: "train", y: 40 },
{ x: "subway", y: 34 },
{ x: "bus", y: 1 },
{ x: "car", y: 100 },
{ x: "moto", y: 194 }
]
}
];
const MyResponsiveLine = ({ data }) => (
<ResponsiveLine
data={data}
margin={{ top: 20, right: 20, bottom: 60, left: 60 }}
xScale={{ type: 'point' }}
yScale={{ type: 'linear', min: 'auto', max: 'auto', stacked: false, reverse: false }}
yFormat=" >-.2f"
axisBottom={{
orient: 'bottom',
legend: 'Transportation',
legendOffset: 36,
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
}}
axisLeft={{
orient: 'left',
legend: 'Usage',
legendOffset: -40,
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
}}
pointSize={10}
pointColor={{ from: 'color' }}
pointBorderWidth={2}
pointBorderColor={{ from: 'serieColor' }}
pointLabelYOffset={-12}
useMesh={true}
legends={[
{
anchor: 'bottom',
direction: 'row',
justify: false,
translateX: 0,
translateY: 56,
itemSpacing: 10,
itemWidth: 80,
itemHeight: 20,
itemOpacity: 0.85,
symbolSize: 12,
symbolShape: 'circle',
effects: [
{
on: 'hover',
style: {
itemOpacity: 1,},
},
],
},
]}
/>
);
export default function App() {
return <MyResponsiveLine data={data} />;
}
In the code snippet above, we define a data array that will be rendered in our line chart. This data serves as the input for the data prop of the ResponsiveLine component.
The various properties allow us to customize the chart, including margins, axis scales, formatting, legends, and point characteristics.
This video tutorial provides a step-by-step guide on how to implement Nivo graphs into a CoreUI React template, showcasing the process in detail.
In this video, the top five ReactJS chart libraries are reviewed: Recharts, Victory, Visx, Nivo, and React-chartjs-2, helping you choose the best option for your project.
Conclusion
By utilizing Nivo, we can efficiently add line charts to our React applications, enhancing the visual representation of data for users.