GraphQL

Getting Started With React And GraphQL


Subscribe On YouTube

DemoCode

GraphQL is a way to send data over HTTP and is often presented as a revolutionary new way to think about APIs and seen as the successor of REST (Representational State Transfer). Indeed GraphQL is able to overcome major shortcomings of REST.

GraphQL can be user in any application, web application or mobile app. In this tutorial you’ll learn how to use GraphQL in a React web application. To make use of GraphQL inside your React project we’ll be using the React Apollo library.

Setting Up The Project

To get started we first need to setup a new React project. The easiest way to do so is to use create-react-app. This script creates a new React project with zero build configuration. The project’s website can be found at https://github.com/facebook/create-react-app.

To make use of create-react-app you simply need to make sure that Node.js is installed on your system. There is no need to install create-react-app before using it. Instead the Node.js npx command can be used in the following way:

$ npx create-react-app react-graphql
$ cd react-graphql
$ npm start

This is initiating a new basic React project in the newly created project folder react-graphql. By using the npm start command the live-reloading development web server is started and the output of the default React project can be accessed in the browser:

Installing Dependencies

The next step is to install needed dependencies.

The following packages needs to be installed:

  • apollo-boost: Package containing everything you need to set up Apollo Client
  • react-apollo: View layer integration for React
  • graphql-tag: Necessary for parsing your GraphQL queries
  • graphql: Also parses your GraphQL queries

The installation of these dependencies can be done by using the following NPM command:

$ npm install apollo-boost react-apollo graphql-tag graphql

Exploring The Initial Project Structure

Having installed the dependencies we’re ready to take a look at the initial project structure:

The important parts of the project are located in the src folder. The main entry point of the React application can be found in index.js. The code contained in this file is making sure that App component is rendered out to the DOM element with ID root.

The implementation of App component can be found in App.js.

Creating An Instance Of ApolloClient

In order to be able to access a GraphQL service from our React application we need to create an instance of ApolloClient first. This is done in App.js by adding the following code:

import ApolloClient from "apollo-boost";

const client = new ApolloClient({
  uri: "[Insert URI of GraphQL endpoint]"
});

First ApolloClient is imported from the apollo-boost library. A new instance of ApolloClient is created and stored in client. To create a new instance of ApolloClient you need to pass a configuration object to the constructor. This object must contain the uri property. The value of this property must be replaced which the URI of the GraphQL endpoint which should be accessed.

Creating A GraphQL Endpoint

To create an Apollo endpoint which can be used as the back-end for our React application you can choose between different options:

  • Use Apollo Launchpad to create a GraphQL server online. Launchpad is an in-browser GraphQL server playground. You can write a GraphQL schema example in JavaScript, and instantly create a serverless, publicly-accessible GraphQL endpoint.
  • Use a preconfigured Apollo Launchpad like https://launchpad.graphql.com/vm8mjvrnv3. This Launchpad exposes a GraphQL Online Courses API which we will be using for the following implementation steps. The corresponding endpoint of that Launchpad is https://vm8mjvrnv3.lp.gql.zone/graphql, so that the value of the uri property needs to be set to that value:
import ApolloClient from "apollo-boost";

const client = new ApolloClient({
  uri: "https://vm8mjvrnv3.lp.gql.zone/graphql"
});

Connecting ApolloClient To Your React App

Having established a connection to the GraphQL endpoint by using ApolloClient we now need to connect the instance of ApolloClient to the React app. To do so, please make sure to add the following lines of code in App.js:

import { ApolloProvider } from "react-apollo";

...

const App = () => (
  <ApolloProvider client={client}>
    <div>
      <h2>My first Apollo app</h2>
    </div>
  </ApolloProvider>
);

Fist ApolloProvide is imported from the react-apollo library. The <ApolloProvider> element is then used in the component’s JSX code and is containing the template code which is used to render the component.

Using Query Component To Request Data

Within the src folder create a new file Courses.js and insert the following code:

import React from 'react';
import { Query } from "react-apollo";
import gql from "graphql-tag";

const Courses = () => (
  <Query
    query={gql`
      {
        allCourses {
          id
          title
          author
          description
          topic
          url
        }
      }
    `}
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Loading...</p>;
      if (error) return <p>Error :(</p>;

      return data.allCourses.map(({ id, title, author, description, topic, url }) => (
        <div key={id}>
          <p>{`${title} by ${author}`}</p>
        </div>
      ));
    }}
  </Query>
);

export default Courses;

This is the implementation of the Courses component. To retrieve data from the GraphQL endpoint this component makes use of another component from the React Apollo library: Query. The Query component makes it extremely easy to embed the GraphQL query directly in the JSX code of the component. Furthermore the Query component contains a callback method which is invoked once the GraphQL query is executed.

Here we’re using the JavaScript map method to generate the HTML output for every single course record which is available in data.allCourses.

Adding A Course Component

So far the output of courses is done within the Courses component. In the next step we’re going to introduce a new component to our project: Course. This component should then contain the code which is needed to output a single course. Once this component is available in can be used in Courses component.

First let’s add a new file Course.js to the project and insert the following lines of code:

import React from 'react';

const Course = (props) => (
    <div key={props.course.id}>
        <p>{`${props.course.title} by ${props.course.author}`}</p>
    </div>
);

export default Course;

The implementation of this component is quite simple. The current course is handed over to Course component as a property and is available via props.course.

In order to make use of Course component in Courses component we first need to make sure that it’s imported in file Courses.js:

import Course from './Course';

Now this component can be used to output each course inside the callback function which is passed to the call of map:

return data.allCourses.map((currentCourse) => (
    <Course course={currentCourse} />
));

Adding Bootstrap

Because the user interface of our sample React application should look a little nicer, we’re going to use the Bootstrap framework in the next step. To add Bootstrap to the project just use the following NPM command:

$ npm install bootstrap

With this command we’re making sure that the Bootstrap framework is installed in the node_modules subfolder of our project. Next we need to import bootstrap.min.css from that location in index.js:

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

With the import statement in place it’s possible to make use of Bootstrap’s CSS classes.

First in App.js:

const App = () => (
  <ApolloProvider client={client}>
    <div className="container">
      <nav className="navbar navbar-dark bg-primary">
        <a className="navbar-brand" href="#">React and GraphQL - Sample Application</a>
      </nav>
      <div>
        <Courses />
      </div>
    </div>
  </ApolloProvider>
);

Second in Course.js:

import React from 'react';

const Course = (props) => (
    <div className="card" style={{'width': '100%', 'marginTop': '10px'}}>
        <div className="card-body">
        <h5 className="card-title">{props.course.title}</h5>
        <h6 className="card-subtitle mb-2 text-muted">by {props.course.author}</h6>
        <p className="card-text">{props.course.description}</p>
        <a href={props.course.url} className="card-link">Go to course ...</a>
        </div>
    </div>
);

export default Course;

The final result should then look like the following:

Conclusion

With the release of React Apollo 2.1 it’s easier than ever to configure and connect Apollo to your React application. By using the brand new Query component you’re able to embed the GraphQL query inside your component. Using higher order components (like before) is no longer needed.

 

ONLINE COURSE: GraphQL with React: The Complete Developers Guide

Check out the great GraphQL with React: The Complete Developers Guide course with thousands of students already enrolled:

GraphQL with React: The Complete Developers Guide

  • Learn and master GraphQL by building real web apps with React and Node
  • Build amazing single page applications with React JS and GraphQL
  • Realize the power of building flexible data schemas
  • Master fundamental concepts behind structuring GraphQL servers
  • Be the engineer who explains how GraphQL works to everyone else, because you know the fundamentals so well

Go To Course

ONLINE COURSE: The Complete React Web App Developer Course

Check out the great Complete React Web App Developer Course by Andrew Mead with thousands of students already enrolled:

The Complete React Web App Developer Course

  • You’ll learn how to develop, test, and deploy React web applications
  • Learn how to setup and automate testing using Karma and Mocha
  • Understand the rich ecosystem of 3rd-party libraries like Redux and Webpack
  • Learn to style applications using the Foundation framework

Go To Course


Using and writing about best practices and latest technologies in web design & development is my passion.