Creating a Basic Bar Chart with TanStack React Charts and useState Hook
Demonstrate how to set up a basic bar chart component using the TanStack React Charts library and manage its data with React's useState hook.
import React, { useState } from 'react';
import { Chart } from 'react-charts';
First, we import necessary hooks from React and the Chart component from the react-charts library.
function BarChartComponent() {
const [data, setData] = useState([
{
label: 'Series 1',
data: [{ x: 'Jan', y: 10 }, { x: 'Feb', y: 20 }, { x: 'March', y: 5 }]
}
]);
Define a component and use the useState hook to manage the data for our bar chart. The data consists of a label for the dataset and a series of x (category) and y (value) pairs.
const axes = React.useMemo(() => [
{ primary: true, type: 'ordinal', position: 'bottom' },
{ type: 'linear', position: 'left' }
], []);
Setup axes configurations for the chart. An ordinal axis for the categories on the bottom and a linear axis for the values on the left.
return (
<Chart
data={data}
axes={axes}
series={{ type: 'bar' }}
/>
);
}
Render the Chart component, passing the data, axes configurations, and specifying the series type as 'bar' to render a bar chart.
export default BarChartComponent;
Finally, export the component so it can be used in other parts of the application.