Home » How to Visualize CSV Data in React JS

How to Visualize CSV Data in React JS

how to create charts with csv data in react js

In this tutorial, we will explore how to create dynamic charts using CSV data in a React JS application. We will use the Recharts library, which provides a set of charting components that are easy to integrate and highly customizable.

As you can see in the above demo video, we have a file input element to get the CSV file then we parse its contents, and visualize the data using line and bar charts.

How to Create Charts with CSV Data in React

Step 1: Installing Dependencies

First, we will install the required recharts library using the below command.

npm install recharts

Step 2: Importing Dependencies

Now, Inside our App.js component we will import the necessary components from the recharts library. Additionally, import the useState hook from React.

import React, { useState } from "react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  BarChart,
  Bar,
} from "recharts";

Step 3: Initializing State

const App = () => {
  const [data, setData] = useState([]);
  const [fileSelected, setFileSelected] = useState(false);
  // ...
}

Inside the App functional component, initialize the state using the useState hook. We will have two state variables: data and fileSelected. The data variable will store the parsed CSV data, and the fileSelected variable will track whether a file has been selected or not.

Step 4: Handling File Change

const handleFileChange = (event) => {
  console.log("event:", event.target.files[0]);
  const file = event.target.files[0];
  const reader = new FileReader();

  reader.onload = (e) => {
    const contents = e.target.result;
    const lines = contents.split("\n");
    const header = lines[0].split(",");
    const parsedData = [];

    for (let i = 1; i < lines.length; i++) {
      const line = lines[i].split(",");
      const item = {};

      for (let j = 0; j < header.length; j++) {
        const key = header[j].trim();
        const value = line[j].trim();
        item[key] = value;
      }

      parsedData.push(item);
    }

    setData(parsedData);
  };

  if (file) {
    reader.readAsText(file);
    setFileSelected(true);
  }
};

Next, The handleFileChange function takes an event parameter, which is triggered when the user selects a file using the <input type="file" /> element. Inside this function, we read the selected file using the FileReader API. 

We then parse the contents of the file into an array of objects, where each object represents a row in the CSV file. The setData function is used to update the state with the parsed data.

Step 5: Rendering the User Interface

In the return statement, we render the UI elements.

return (
  <div>
    <input type="file" accept=".csv" onChange={handleFileChange} />

    {!fileSelected && <p>Please select a file.</p>}

    {data.length > 0 && (
      <div className="charts-container">
        {/* Line Chart */}
        <div className="chart">
          <LineChart
            width={500}
            height={300}
            data={data}
            margin={{
              top: 5,
              right: 30,
              left: 0,
              bottom: 5,
            }}
          >
            {/* ... */}
          </LineChart>
        </div>

        {/* Bar Chart */}
        <div className="chart">
          <BarChart width={500} height={300} data={data}>
            {/* ... */}
          </BarChart>
        </div>
      </div>
    )}
  </div>
);

We start by rendering an <input type="file" /> element that allows the user to select a CSV file. The onChange event is bound to the handleFileChange function we defined earlier.

Next, we check if a file has been selected (fileSelected state) and display a message if no file is selected.

If data contains parsed CSV data, we render the charts. We use conditional rendering to display the charts only when data is available. The charts are wrapped inside a <div className="charts-container"> for styling purposes.

Step 6: Rendering the Line Chart

Inside the LineChart component, we configure the chart’s properties and pass in the parsed CSV data.

<LineChart
  width={500}
  height={300}
  data={data}
  margin={{
    top: 5,
    right: 30,
    left: 0,
    bottom: 5,
  }}
>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="Category" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="Value" stroke="#CA4F8E" strokeWidth="3" />
</LineChart>

The LineChart component is configured with a fixed width and height. We pass in the data state as the chart’s data source.

Inside the LineChart component, we configure various elements:

  • CartesianGrid: Displays grid lines in the chart.
  • XAxis: Represents the X-axis with data from the “Category” key.
  • YAxis: Represents the Y-axis.
  • Tooltip: Displays tooltips when hovering over the chart.
  • Legend: Displays a legend for the chart.
  • Line: Renders a line in the chart using the "Value" key from the data. The line’s stroke color is set to "#CA4F8E" with a strokeWidth of 3.

Step 7: Rendering the Bar Chart

Similarly, we configure the BarChart component to render the bar chart.

<BarChart width={500} height={300} data={data}>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="Category" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Bar dataKey="Value" fill="#CA4F8E" />
</BarChart>

The BarChart component is also configured with a fixed width and height. We pass in the data state as the chart’s data source.

Inside the BarChart component, we configure similar elements:

  • CartesianGrid: Displays grid lines in the chart.
  • XAxis: Represents the X-axis with data from the "Category" key.
  • YAxis: Represents the Y-axis.
  • Tooltip: Displays tooltips when hovering over the chart.
  • Legend: Displays a legend for the chart.
  • Bar: Renders bars in the chart using the "Value" key from the data. The bar color is set to "#CA4F8E".

Also, check out:

App.js Complete Code:

import React, { useState } from "react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  BarChart,
  Bar,
} from "recharts";

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

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
      const contents = e.target.result;
      const lines = contents.split("\n");
      const header = lines[0].split(",");
      const parsedData = [];

      for (let i = 1; i < lines.length; i++) {
        const line = lines[i].split(",");
        const item = {};

        for (let j = 0; j < header.length; j++) {
          const key = header[j].trim();
          const value = line[j].trim();
          item[key] = value;
        }

        parsedData.push(item);
      }

      setData(parsedData);
    };

    if (file) {
      reader.readAsText(file);
      setFileSelected(true);
    }
  };

  return (
    <div>
      <input type="file" accept=".csv" onChange={handleFileChange} />

      {!fileSelected && <p>Please select a file.</p>}

      {data.length > 0 && (
        <div className="charts-container">
          <div className="chart">
            <LineChart
              width={500}
              height={300}
              data={data}
              margin={{
                top: 5,
                right: 30,
                left: 0,
                bottom: 5,
              }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="Category" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Line
                type="monotone"
                dataKey="Value"
                stroke="#CA4F8E"
                strokeWidth="3"
              />
            </LineChart>
          </div>

          <div className="chart">
            <BarChart width={500} height={300} data={data}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="Category" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Bar dataKey="Value" fill="#CA4F8E" />
            </BarChart>
          </div>
        </div>
      )}
    </div>
  );
};

export default App;

Output:

display csv data in charts using react

Conclusion

In this blog post, we learned how to create dynamic charts with CSV data in a React JS application. By using the “recharts” library, we were able to render both Line and Bar charts based on the parsed CSV data. This allows us to visualize and analyze the data in an interactive and informative way. Feel free to customize the charts further based on your specific requirements. Happy charting!

Leave a Reply

Your email address will not be published.