Connecting React with JSON:API or GraphQLfor Drupal 8 , 9 , 10 , and 11

Last updated :  

In this lesson, we will explore how to connect React, a popular JavaScript library for building user interfaces, with Drupal's backend using JSON:API or GraphQL. This step is essential to leveraging Drupal's powerful content management capabilities while providing a modern, dynamic user experience.

Understanding JSON:API and GraphQL in Drupal

Before diving into the technical implementation, let's briefly understand what JSON:API and GraphQL are:

  • JSON:API: It is a specification that defines how clients should request and modify data, and how servers should respond to those requests. Drupal provides support for JSON:API out of the box, making it easy to expose your content in a standardized format.
  • GraphQL: A query language for APIs, GraphQL empowers clients to request precisely the data they need. It allows for greater flexibility and efficiency, especially when dealing with complex data structures. For Drupal, GraphQL modules are available to set up GraphQL endpoints.

Setting Up React to Consume JSON:API

The process of connecting React to your Drupal backend through JSON:API involves making HTTP requests from your React application to the JSON:API endpoints exposed by your Drupal installation.

Step 1: Create a React App

If you haven't done so already, create a new React application using Create React App:

npx create-react-app my-drupal-react-app

Navigate into your project directory:

cd my-drupal-react-app

Step 2: Fetching Data from JSON:API

You can now utilize the fetch API or Axios, which you learned about in the previous lesson, to request data:

import React, { useState, useEffect } from 'react';

function ArticleList() {
    const [articles, setArticles] = useState([]);

    useEffect(() => {
        fetch('https://example-drupal-site.com/jsonapi/node/article')
            .then(response => response.json())
            .then(data => setArticles(data.data))
            .catch(error => console.error('Error fetching articles:', error));
    }, []);

    return (
        <div>
            <h2>Articles</h2>
            <ul>
                {articles.map(article => (
                    <li key={article.id}>{article.attributes.title}</li>
                ))}
            </ul>
        </div>
    );
}

export default ArticleList;

In this example, we fetch articles from a Drupal endpoint and display them with their titles. You can manipulate the retrieved data as needed to fit your app's requirements.

Using GraphQL for Enhanced Flexibility

To use GraphQL with Drupal, you'll need to set up a GraphQL endpoint via the GraphQL module. Once set up, React can query this endpoint for more efficient data retrieval.

Step 1: Setting Up GraphQL in Drupal

Install and enable the graphql module in Drupal. This can be done through the Drupal admin UI or using Drush:

composer require drupal/graphql

Step 2: Making a GraphQL Query in React

After setting up GraphQL, use Apollo Client to execute GraphQL queries in your React app:

import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://example-drupal-site.com/graphql',
  cache: new InMemoryCache()
});

const GET_ARTICLES = gql`
  query GetArticles {
    nodeQuery {
      entities {
        ... on NodeArticle {
          nid
          title
        }
      }
    }
  }
`;

function ArticleList() {
  const { loading, error, data } = useQuery(GET_ARTICLES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h2>Articles</h2>
      <ul>
        {data.nodeQuery.entities.map(article => (
          <li key={article.nid}>{article.title}</li>
        ))}
      </ul>
    </div>
  );
}

function App() {
  return (
    <ApolloProvider client={client}>
      <ArticleList />
    </ApolloProvider>
  );
}

export default App;

This React setup demonstrates querying a GraphQL endpoint and utilizing the results within components. The Apollo Client provides an efficient way to manage and cache GraphQL data, making your application more performant and responsive.

Conclusion

By integrating React with either JSON:API or GraphQL, you've expanded your headless Drupal capabilities, allowing for a dynamic and modern frontend application. In our next lesson, we'll explore how to fetch Drupal data in Vue.js applications, continuing our journey into the versatility of headless CMS architectures.