Setting Up a Basic Line Chart with TanStack React Charts
Demonstrate how to set up a basic line chart to display stock price trends over time using TanStack React Charts within a React component. Includes data setup and chart configuration.
import React from 'react';
import { Chart } from '@tanstack/react-charts';
Import React and Chart component from TanStack React Charts.
const MyLineChart = () => {
const data = React.useMemo(
() => [
{
label: 'Series 1',
data: [{ x: new Date('2022-01-01'), y: 30 }, { x: new Date('2022-02-01'), y: 10 }, { x: new Date('2022-03-01'), y: 50 }]
}
],
[]
);
Define your component and memoize the data to be used by the chart. This example uses static data for demonstration.
const axes = React.useMemo(
() => [
{ primary: true, type: 'time', position: 'bottom' },
{ type: 'linear', position: 'left' }
],
[]
);
Define the axes for the chart. Here a time axis is defined as the primary bottom axis and a linear axis as the left axis.
return (
<Chart
options={{
data,
axes,
initialWidth: 600,
initialHeight: 300,
primaryCursor: true,
secondaryCursor: true,
tooltip: true
}}
/>
);
};
Render the Chart component with the defined options including data and axes. Cursors and tooltips are enabled for interactivity.
export default MyLineChart;
Export the line chart component.