DEV Community

Cover image for Using AG Grid with React and Next.js
Alan Richardson for AG Grid

Posted on • Originally published at blog.ag-grid.com on

Using AG Grid with React and Next.js

Using AG Grid with React and Next.js

This post contributed to the AG Grid blog by Veronica Stork.

If you’ve worked with React recently, you’ve likely heard of Next.js, a popular React framework with a great developer experience. Next.js combines well with many other technologies, including AG Grid, a feature-packed data grid with over 1.2 million monthly downloads and over 80 percent of Fortune 500 companies using the Enterprise edition.

Next.js is known for its painless implementation of advanced features and superior developer experience—it makes it easy to create production-ready web apps with zero configuration. Out of the box, it includes hybrid static and server rendering, image optimization, TypeScript support, easy routing, and more.

Meanwhile, AG Grid can process over 150,000 updates per second, making it the perfect choice for livestreaming data. It can create integrated and standalone charting and it also comes with the ability to select, filter, sort, and edit rows, making it an all-around useful tool for wrangling complex data tables.

Next.js’s and AG Grid are highly complementary. Together, they can be used to create internal dashboards, finance apps, data models, and anything else that requires the fast, accurate handling of large amounts of data.

In this tutorial, you’ll learn how to create a Next.js app that utilizes Next’s native API routing to fetch data and display it on the frontend using AG Grid. Then, you will create some simple tests using Jest and the React Testing Library.

Implementing AG Grid with Next.js

Let’s get started!

You can check out the sample app for this tutorial in action here and refer to the full code in this GitHub repo.

Get Some Data

First things first: you’ll need some data to display in your grid. For the sample app, this tutorial uses Mockaroo to generate one hundred records with first_name, last_name, job_title, office, email, and phone fields.

To generate these records using Mockaroo, fill in the Field Name and Type for each field you want to create:

Using AG Grid with React and Next.js

To find the appropriate field types, you can either browse the provided categories or type a keyword in the search bar:

Using AG Grid with React and Next.js

By default, Mockaroo will generate one thousand rows of data. You can change this number by editing the text box labeled “# Rows”. When you are done, click Download Data on the bottom of the screen. This will download a CSV file to your computer.

In the demo app, the CSV file has been imported into a hosted ElephantSQL database using Postico, a PostgreSQL client for Mac. While this tutorial will show you how to build the app using a PostgreSQL database like ElephantSQL, you can use whatever type of database you prefer for your own app.

To import the file into ElephantSQL, sign in and create a new instance. Give it a name, select the region, and click Review. If everything looks good, click Create Instance.

This automatically brings you to a list of your instances. Click on the name of the instance you just created, and copy the URL listed under Details.

Now, go to Postico and click New Favorite. If you have copied your database URL to the clipboard, Postico will automatically be populated with your database information. Click Connect to connect to your database:

Using AG Grid with React and Next.js

Once you have connected, click + Table. Give your table a name then click the + Column button to add columns for each of the fields you generated in Mockaroo. Then, go to File > Import CSV and choose the mock data file. Match the columns from the CSV to the columns in your database, and click Import.

Now that you have your database set up, it’s time to create your app!

Create Your Next.js App

Create your Next.js app easily by running this command: npx create-next-app@latest <app_name>.

To add AG Grid to your project, install it using npm by running npm install --save ag-grid-community ag-grid-react.

If you are using a PostgreSQL database, you should also install pg by running npm install pg. If you are using a different type of database, you may need to install a different library.

A Note about Linting

Next.js provides linting capabilities out of the box using ESLint. Check your package.json file, and you should see ”lint”: “next lint” listed under scripts. If it is not there, add it. To run the linter, run npm run lint. For more information about linting in Next.js, check out this page in their documentation.

Connect to Your Database

To create a connection to your database, start by making a folder called utils at the top level of your app, and then create a file called db.js inside. If you are using a PostgreSQL database, the contents of db.js should look like this:

import { Pool } from 'pg';

let connection = new Pool({
    connectionString:
     process.env.CONNECTION_STRING
  });

export default connection;

Enter fullscreen mode Exit fullscreen mode

A note on security: Since it contains private credentials, the process.env.CONNECTION_STRING variable should be stored in a secure location. In the demo app, which is hosted using Vercel, this variable is stored using Environment Variables under Settings. Many hosting services have this very convenient security option.

Now that you have a connection to your database, create a file called staff.js under pages > api. Next.js allows you to create your API without any need to build your own separate backend. Any file you put in the api folder is automatically treated as an API endpoint by Next.js. You will utilize that functionality here.

The staff.js file should look something like this:

import connection from ‘../../utils/db’;

export default async function handler(req, res) {
  try {
    const query = 'SELECT * FROM staff';
    const staff = await connection.query(query);
    res.send(staff);
  } catch (error) {
    console.log(error);
  }
}

Enter fullscreen mode Exit fullscreen mode

In this code, you are connecting to the database using the db.js connection function you just wrote, then querying the database to get all of the rows from the staff table. That data is sent as a response when this API endpoint is accessed.

Now that you have a connection to your database and a way to access it, it’s time to work on the frontend.

Set Up Routes

Routing in Next.js is easy. If you put a file that exports a React component in the pages folder, it is automatically associated with a route based on the file name. For example, a file called about.js located in the pages folder would map to /about. The index.js file maps to the root (/). Next.js also supports nested routes, dynamic routes, and client-side route transitions. To learn more about routing in Next.js, check out their documentation on the subject.

For this app, you will be using the index.js file to display your grid. Delete the contents of the Home component of the default index.js file located in the pages folder.

Set Up AG Grid

Now it’s time to set up your grid! In index.js , make the following imports:

import { useState, useEffect } from ‘react’;
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';

Enter fullscreen mode Exit fullscreen mode

Next, set up your columns using the useState hook, like this:

 const [columnDefs] = useState([
    { headerName: 'First Name', field: 'first_name' },
    { headerName: 'Last Name', field: 'last_name' },
    { headerName: 'Job Title', field: 'job_title' },
    { field: 'office' },
    { field: 'email’ },
    { field: ‘phone’ }
  ]);

Enter fullscreen mode Exit fullscreen mode

If you leave out the headerName property, AG Grid will automatically title the columns using the field.

After you have your columns set up, you need to write some code to fetch the data from the API endpoint you set up earlier.

First, you will use the useState hook to create a state variable (rowData) to hold the data, and a setRowData function you can use to update rowData.

Then, you’ll access the /api/staff endpoint using fetch from within the useEffect hook and use setRowData to store the data returned from the database in the rowData variable. The code should look like the following:

  const [rowData, setRowData] = useState([]);

  useEffect(() => {
    fetch('../api/staff')
      .then((response) => response.json())
      .then((data) => setRowData(data.rows));
  }, []);

Enter fullscreen mode Exit fullscreen mode

Once you fetch the data, you will display it using an AgGridReact component. Create this component in the return statement using the following code:

    <div 
      className="ag-theme-alpine"
      style={{ height: '600px' }}
    >
      <AgGridReact
        id="staff_grid"
        rowData={rowData}
        columnDefs={columnDefs}
        style={{ height: '100%', width: '100%' }}
      ></AgGridReact>
    </div>

Enter fullscreen mode Exit fullscreen mode

Your grid must reference the rowData returned from the API call as well as the columnDefs object you defined earlier. As long as both of these are present and formatted correctly, AG Grid will automatically take care of displaying your grid.

The grid should look something like this:

Using AG Grid with React and Next.js

Build Some Tests

You can build tests for your Next.js AG Grid app using a variety of tools. One good option is Jest. Next.js has built-in configuration for Jest, which is often used with the React Testing Library to perform unit testing.

To set up Jest, run the following: npm install --save-dev jest @testing-library/react @testing-library/jest-dom.

Next, create a jest.config.js file at the top level of your project. The config file should contain the following code, which can also be found in the testing section of the Next.js docs:

const nextJest = require('next/jest')

const createJestConfig = nextJest({
   dir: './',
})

const customJestConfig = {
  ['<rootDir>/jest.setup.js'],
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
}

module.exports = createJestConfig(customJestConfig)

Enter fullscreen mode Exit fullscreen mode

Edit package.json to include ”test”: “jest –watch” under scripts. Then, create a tests folder in your project’s root directory, with a file named aggrid.test.jsx in that folder. This is where you will write your tests.

Generally, you will want to test to see whether the grid is being rendered as expected and if it is being populated with data correctly. The following simple test checks to see if the AG Grid component with the id of staff_grid exists in the document:

describe('AG Grid Tests', () => {

  it('renders the grid', () => {
    expect(document.querySelector("#staff_grid")).toBeInTheDocument;
  })

})


Enter fullscreen mode Exit fullscreen mode

Similarly, with a test like the following, you can check to see if the columns are being rendered:

  it('renders the columns', () => {
    expect(document.querySelector(`.ag-cell[col-id="first_name"]`)).toBeInTheDocument;
    expect(document.querySelector(`.ag-cell[col-id="last_name"]`)).toBeInTheDocument;
    expect(document.querySelector(`.ag-cell[col-id="job_title"]`)).toBeInTheDocument;
    expect(document.querySelector(`.ag-cell[col-id="email"]`)).toBeInTheDocument;
    expect(document.querySelector(`.ag-cell[col-id="office"]`)).toBeInTheDocument;
    expect(document.querySelector(`.ag-cell[col-id="phone"]`)).toBeInTheDocument;
  })

Enter fullscreen mode Exit fullscreen mode

To run this test, simply open up a new console while your app is running and run npm run test. You will see the results right in your console:

Using AG Grid with React and Next.js

For a great write-up on testing AG Grid with Jest and React Testing Library, check out this blog post by Alan Richardson, AG Grid’s digital marketing head.

Develop, Preview, Ship!

When you use Next.js, it’s easy to move fast as you develop, preview, and ship. Vercel, the company responsible for Next.js, also provides an excellent hosting service. You can deploy easily to Vercel using their GitHub integration. Then, you can preview deployments with your teammates and get rapid feedback after every code change before you ship.

The easiest way to deploy your app on Vercel is to import a GitHub repo. If you haven’t already, initialize the local directory as a Git repository, commit the files, and push them to a remote branch on GitHub. For more detailed information about adding a locally hosted project to GitHub, check out this tutorial explaining the process.

Once your app’s code is on GitHub, sign in to Vercel using your GitHub account and create a new project by clicking the New Project button on the top right side of the screen:

Using AG Grid with React and Next.js

Next, choose the correct repo from under Import Git Repository.

That’s all you need to do! Now, your app will update whenever you push to your main branch.

Conclusion

In this article, you learned how to create a Next.js app that uses AG Grid to display a simple data grid. AG Grid contains a ton of features; it can handle large amounts of data, livestreaming updates, and integrated charting. You can also use it to pivot, filter, sort, and select data from tables, and that’s not all of its capabilities. To learn more about AG Grid, check out their documentation.

If you want to expand on the demo app described in this tutorial, go to the GitHub repo and fork and clone it. The app includes some expanded functionality that is not covered in this tutorial, but even then, it doesn’t scratch the surface of what is possible with Next.js and AG Grid.

Top comments (0)