Visualizing Data in React Native: A Guide to Charting Libraries

Building the Finance Tracking App

Our app will have four screens: three for user input and one for displaying charts. We’ll focus on the reports screen, which will feature three types of charts: pie, bar, and line charts.

Setting Up the Project

To get started, create a new React Native project and install the required packages:

npm install react-navigation react-native-paper react-native-chart-kit

You can find the full list of dependencies in the package.json file.

Creating the Charts

We’ll start by creating the pie chart component, which will display the transaction types, expense types, income types, savings types, and investment types.


import { PieChart } from 'eact-native-chart-kit';

const PieChartComponent = () => {
  const data = [
    { name: 'Transaction', value: 20 },
    { name: 'Expense', value: 30 },
    { name: 'Income', value: 40 },
    { name: 'Savings', value: 10 },
    { name: 'Investment', value: 20 },
  ];

  const chartConfig = {
    backgroundColor: '#fff',
    backgroundGradientFrom: '#fff',
    backgroundGradientTo: '#fff',
    color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
  };

  return (
    <PieChart
      data={data}
      width={200}
      height={200}
      chartConfig={chartConfig}
      accessor="value"
      backgroundColor="transparent"
      paddingLeft="15"
      absolute
    />
  );
};

Next, we’ll create the bar chart component, which will display the monthly income and expenses.


import { BarChart } from 'eact-native-chart-kit';

const BarChartComponent = () => {
  const data = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    datasets: [
      {
        data: [20, 30, 40, 50, 60],
        color: (opacity = 1) => `rgba(255, 134, 159, ${opacity})`,
      },
      {
        data: [10, 20, 30, 40, 50],
        color: (opacity = 1) => `rgba(131, 167, 235, ${opacity})`,
      },
    ],
  };

  const chartConfig = {
    backgroundColor: '#fff',
    backgroundGradientFrom: '#fff',
    backgroundGradientTo: '#fff',
    color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
  };

  return (
    <BarChart
      style={{ flex: 1 }}
      data={data}
      width={200}
      height={200}
      chartConfig={chartConfig}
      yAxisSuffix="k"
      yAxisInterval={1}
      xAccessor="labels"
      fromZero={true}
      showValuesOnTopOfBars={true}
    />
  );
};

Finally, we’ll create the line chart component, which will compare income, savings, and investments over time.


import { LineChart } from 'eact-native-chart-kit';

const LineChartComponent = () => {
  const data = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    datasets: [
      {
        data: [20, 30, 40, 50, 60],
        color: (opacity = 1) => `rgba(255, 134, 159, ${opacity})`,
      },
      {
        data: [10, 20, 30, 40, 50],
        color: (opacity = 1) => `rgba(131, 167, 235, ${opacity})`,
      },
      {
        data: [5, 10, 15, 20, 25],
        color: (opacity = 1) => `rgba(255, 214, 159, ${opacity})`,
      },
    ],
  };

  const chartConfig = {
    backgroundColor: '#fff',
    backgroundGradientFrom: '#fff',
    backgroundGradientTo: '#fff',
    color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
  };

  return (
    <LineChart
      style={{ flex: 1 }}
      data={data}
      width={200}
      height={200}
      chartConfig={chartConfig}
      bezier
      fromZero={true}
      showValuesOnTopOfBars={true}
    />
  );
};

Getting the Data

To populate our charts, we’ll need to retrieve data from our SQLite database using the React Native SQLite storage library.


import { SQLite } from 'eact-native-sqlite-storage';

const db = SQLite.openDatabase({ name: 'finance.db', location: 'default' });

const getTransactionsByType = () => {
  return db.executeSql('SELECT type, SUM(amount) as total FROM transactions GROUP BY type');
};

const getExpenseCategories = () => {
  return db.executeSql('SELECT category, SUM(amount) as total FROM expenses GROUP BY category');
};

//...

Putting it All Together

Once we have our data, we’ll update the state values and render the charts with the corresponding data. We’ll also add conditions to show each chart based on the user’s selection.


class ReportsScreen extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      transactionsByType: [],
      expenseCategories: [],
      //...
    };
  }

  componentDidMount() {
    getTransactionsByType().then((result) => {
      this.setState({ transactionsByType: result });
    });

    getExpenseCategories().then((result) => {
      this.setState({ expenseCategories: result });
    });

    //...
  }

  render() {
    return (
      <View>
        {this.state.transactionsByType.length > 0 && (
          <PieChartComponent data={this.state.transactionsByType} />
        )}
        {this.state.expenseCategories.length > 0 && (
          <BarChartComponent data={this.state.expenseCategories} />
        )}
        {this.state.incomeCategories.length > 0 && (
          <LineChartComponent data={this.state.incomeCategories} />
        )}
      </View>
    );
  }
}

Check out the full source code of the app in its GitHub repo for more information.

Leave a Reply