How To Use React With Apollo GraphQL

In this tutorial I'll teach you how to use React with Apollo GraphQL client. You'll learn how to query GraphQL server and render query results, by building a simple React application.

As a bonus, I'll explain to you an important software development principle which will help you to write higher quality code.

We'll be building a simple React application that renders a list of jobs that require GraphQL knowledge. We'll get this list of jobs by querying a GraphQL server.

Let's take a look at how our app will work. The first screen will display a title and a button:

Application screenshot
Figure 1. Our application.

User will click the Load GraphQL jobs button and then the loading spinner will be rendered instead of the button:

Application screenshot
Figure 2. Our application.

Finally, we'll render the number of jobs and the list of jobs, displaying job title, company name and locations for each job:

Application screenshot
Figure 3. Our application.

Here you can play with the app and you can find the full source code in this GitHub repository.

Our application will be made of two React components:

  1. Jobs
  2. Job

Jobs component will render the app title, the button and the loading indicator, as well as a list of jobs. Each job will be rendered by the Job component.

Let's create our Job component first:


import React from "react";

function getCitiesLabel(cities) {
  return cities.length > 1 ? "Cities" : "City";
}

function getCitiesList(cities) {
  return cities.map((city) => city.name).join(", ");
}

function Job(props) {
  return (
    <a
      href={props.job.applyUrl}
      className="list-group-item list-group-item-action"
    >
      <h3>{props.job.title}</h3>
      <div>
        <strong>Company:</strong> {props.job.company.name}
      </div>
      {props.job.cities.length > 0 && (
        <div>
          <strong>{getCitiesLabel(props.job.cities)}: </strong>
          {getCitiesList(props.job.cities)}
        </div>
      )}
    </a>
  );
}

export default Job;

Code snippet 1. Job.component.js

To be continued…