Skip to content
Go back

Using Strapi GraphQL API with React Frontend

Using Strapi GraphQL API with React Frontend

Introduction

Strapi’s GraphQL plugin provides a powerful API. This guide uses Apollo Client to query and render data in a React application.

Prerequisites

Step 1: Install Apollo Client

npm install @apollo/client graphql

Step 2: Configure Apollo Client

Create src/apolloClient.js:

import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";

const httpLink = createHttpLink({
  uri: "http://localhost:1337/graphql",
});

export const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});

Step 3: Wrap App with Provider

In src/index.js:

import React from "react";
import ReactDOM from "react-dom";
import { ApolloProvider } from "@apollo/client";
import { client } from "./apolloClient";
import App from "./App";

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById("root")
);

Step 4: Fetch Data with Query

In src/components/ArticlesList.js:

import { useQuery, gql } from "@apollo/client";

const GET_ARTICLES = gql`
  query GetArticles($limit: Int) {
    articles(pagination: { limit: $limit }) {
      data {
        id
        attributes {
          title
          content
          publishedAt
        }
      }
    }
  }
`;

export default function ArticlesList({ limit = 5 }) {
  const { loading, error, data } = useQuery(GET_ARTICLES, {
    variables: { limit },
  });

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

  return (
    <ul>
      {data.articles.data.map(({ id, attributes }) => (
        <li key={id}>
          <h3>{attributes.title}</h3>
          <p>{new Date(attributes.publishedAt).toLocaleDateString()}</p>
        </li>
      ))}
    </ul>
  );
}

Step 5: Use Component in App

In src/App.js:

import ArticlesList from "./components/ArticlesList";

function App() {
  return (
    <div>
      <h1>Blog Articles</h1>
      <ArticlesList limit={10} />
    </div>
  );
}

export default App;

Summary

Using Strapi’s GraphQL API with Apollo Client in React allows efficient data fetching and state management, enabling dynamic content rendering in headless CMS setups.


Share this post on:

Previous Post
Migrating Strapi Content Between Environments
Next Post
Monitoring VPS with Prometheus + Grafana