Render a line chart using SVG

To render a line chart in React using SVG, you can create a reusable component that takes data as input and generates the SVG elements accordingly. Here’s an example code snippet that demonstrates how to do this:

import React from 'react';

const LineChart = ({ data, width, height, lineColor }) => {
  const maxValue = Math.max(...data);
  const xScale = width / (data.length - 1);
  const yScale = height / maxValue;

  const points = data.map((value, index) => `${index * xScale},${height - value * yScale}`);

  const pathData = `M${points.join(' L')}`;

  return (
    <svg width={width} height={height}>
      <path d={pathData} fill="none" stroke={lineColor} strokeWidth="2" />
    </svg>
  );
};

export default LineChart;

In this code, the LineChart component receives the following props:

  • data: An array of numeric values representing the y-coordinates of each point on the line.
  • width: The width of the chart in pixels.
  • height: The height of the chart in pixels.
  • lineColor: The color of the line.

The component calculates the necessary dimensions for each point based on the provided props. It then maps over the data array to generate a string of coordinate values for each point on the line. The pathData variable constructs an SVG path string using the generated coordinates.

Finally, the component renders an SVG path element with the d attribute set to pathData. The fill attribute is set to “none” to make the line transparent, and the stroke attribute defines the color of the line using the lineColor prop. The strokeWidth attribute sets the thickness of the line to 2 pixels.

You can use the LineChart component in your application like this:

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

const App = () => {
  const data = [10, 20, 15, 30, 25, 35];
  
  return (
    <div>
      <h1>Line Chart Example</h1>
      <LineChart data={data} width={400} height={300} lineColor="steelblue" />
    </div>
  );
};

export default App;

In this example, we pass an array of numbers (data), along with the desired width, height, and line color to the LineChart component. Adjust these values to match your specific requirements.

Related Posts

Leave a Reply

Your email address will not be published.