?? Creating Dynamic Dashboards with React and Recharts

?? Creating Dynamic Dashboards with React and Recharts


Dashboards play a crucial role in data visualization, enabling businesses and users to make informed decisions quickly. If you're developing a React application and need to present information visually and interactively, Recharts is one of the best libraries available.

In this article, we’ll explore how to build a dynamic dashboard using React and Recharts, highlighting key features and best practices to make your data visualizations more impactful.


?? Why Use Recharts?

Recharts is a charting library built on React and D3.js, offering a simple and efficient way to render dynamic charts. Some of its advantages include:

? Ease of use – Intuitive API based on React components ? Componentization – Allows you to reuse charts throughout your project ? Responsiveness – Charts automatically adapt to different screen sizes ? Built-in animations – Enhances user experience with smooth transitions ? Compatibility – Easily integrates with UI libraries like MUI, Tailwind CSS, and Ant Design

Now that we understand its benefits, let’s create a step-by-step dynamic chart.


?? Building a Simple Chart with Recharts

1?? Installing Dependencies

First, install Recharts in your React project. If you don’t have a project yet, create one with:

npx create-react-app meu-dashboard
cd meu-dashboard
npm install recharts        


2?? Creating Sample Data

Let’s define some sample data to feed our chart. Normally, this data would come from an API, but for this example, we’ll use a static array:

const data = [
  { name: "Jan", vendas: 4000, clientes: 2400 },
  { name: "Fev", vendas: 3000, clientes: 2210 },
  { name: "Mar", vendas: 2000, clientes: 2290 },
  { name: "Abr", vendas: 2780, clientes: 2000 },
  { name: "Mai", vendas: 1890, clientes: 2181 },
];        

Each object contains the month (name), the number of sales (sales), and the number of customers (customers).


3?? Creating the Chart Component

Now, let’s create a line chart to visualize sales and customer trends over the months.

import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

const Dashboard = () => {
  return (
    <ResponsiveContainer width="100%" height={300}>
      <LineChart data={data} margin={{ top: 20, right: 30, left: 20, bottom: 10 }}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Line type="monotone" dataKey="vendas" stroke="#8884d8" strokeWidth={2} />
        <Line type="monotone" dataKey="clientes" stroke="#82ca9d" strokeWidth={2} />
      </LineChart>
    </ResponsiveContainer>
  );
};

export default Dashboard;        

?? Code Explanation:

  • ResponsiveContainer ensures the chart adjusts to different screen sizes.
  • LineChart defines the graph and receives data via data={data}.
  • CartesianGrid adds gridlines for better readability.
  • XAxis and YAxis represent the horizontal and vertical axes.
  • Tooltip displays data when hovering over points.
  • Legend adds a label for each data series.
  • Line represents the plotted data, with different colors for sales and customers.



?? Making the Dashboard More Dynamic

?? Real-Time Data Updates

We can make the chart dynamic by updating the data via an API or WebSockets. Here’s an example using useEffect and fetch:

import { useState, useEffect } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

const Dashboard = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://api.exemplo.com/dados")
      .then((response) => response.json())
      .then((dados) => setData(dados))
      .catch((error) => console.error("Erro ao buscar os dados", error));
  }, []);

  return (
    <ResponsiveContainer width="100%" height={300}>
      <LineChart data={data} margin={{ top: 20, right: 30, left: 20, bottom: 10 }}>
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Line type="monotone" dataKey="vendas" stroke="#8884d8" strokeWidth={2} />
        <Line type="monotone" dataKey="clientes" stroke="#82ca9d" strokeWidth={2} />
      </LineChart>
    </ResponsiveContainer>
  );
};        

?? Key Highlights:

  • We use useState to store the fetched data.
  • useEffect makes an API request to fetch the latest data.
  • The chart automatically updates whenever new data is received.



?? Exploring Other Chart Types

Besides line charts, Recharts supports multiple chart types for different needs:

? BarChart → Bar charts

? PieChart → Pie charts

? AreaChart → Area charts

? RadarChart → Radar charts

Example of a bar chart:

import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer } from 'recharts';

<BarChart data={data}>
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Bar dataKey="vendas" fill="#8884d8" />
  <Bar dataKey="clientes" fill="#82ca9d" />
</BarChart>        


?? Conclusion

Building dynamic dashboards with React and Recharts is an excellent way to turn raw data into powerful insights. With the right combination of charts and interactivity, you can create comprehensive dashboards for various applications, from financial analysis to performance monitoring.

?? Now it’s your turn! Have you used Recharts in your projects? What was your experience? Share your thoughts in the comments! ??

Patrick Cunha

Lead Fullstack Engineer | Typescript Software Engineer | Nestjs | Nodejs | Reactjs | AWS

1 周

This is a well-structured and informative guide to using Recharts with React! I appreciate the clear, step-by-step instructions and practical examples. Definitely a helpful resource for anyone looking to create dynamic dashboards.

回复
Guilherme Luiz Maia Pinto

Back End Engineer | Software Engineer | TypeScript | NodeJS | ReactJS | AWS | MERN | GraphQL | Jenkins | Docker

2 周

Thanks for sharing ??

回复
Rodrigo Modesto

Data Analyst Professional | Data Visualization Specialist | Power BI | SQL | Alteryx | GCP | BigQuery | Python | Figma

2 周

Great overview of Recharts! ?? It’s definitely a solid choice for building dynamic charts in React, especially for devs who want a simple yet powerful charting library.

回复
Alexandre Germano Souza de Andrade

Senior Software Engineer | Backend-Focused Fullstack Developer | .NET | C# | Angular | React.js | TypeScript | JavaScript | Azure | SQL Server

2 周

Nice content Bruno Freitas, thanks for sharing ??

回复
Kaique Perez

Fullstack Software Engineer | Node | Typescript | React | Next.js | AWS | Tailwind | NestJS | TDD | Docker

2 周

Interesting! Thanks for sharing! Bruno Freitas

回复

要查看或添加评论,请登录

Bruno Freitas的更多文章

社区洞察