Start Gatsby with WordPress

Gatsby is now a days roar in progressive web app. In this post, we will develop a workflow to integrate Gatsby with WordPress.

To integrate WordPress with Gatsby, first step is set pretty permalink in WordPress. This enable to using RESTful API from Gatsby app.

To develop this, I use these plugins

These plugins functionality will develop in future. Let’s develop basic
Get gatsby-cli with npm

npm install -g gatsby-cli

After install gatsby-cli, go to destination folder where gatsby application build. Here, get gatsby starter default project by

gatsby new gatsby-wp

After getting this project, lookup folders and files which are really helpful.
After lookup our project, let’s see which we building.

gatsby develop

This will run our app at localhost:8000 in the browser and it look like

After get this, connect gatsby with WordPress. Install gatsby-source-wordpress and gatsby-plugin-sitemap

npm install gatsby-source-wordpress gatsby-plugin-sitemap

Then, open gatsby-config.js file in root and configure gatsby-source-wordpress plugin. Finally, gatsby-config.js file at this point has following code

module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
    description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
    author: `@gatsbyjs`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    `gatsby-plugin-sitemap`,
    {
      resolve: "gatsby-source-wordpress",
      options: {
        // I have created a dummy site for us to use with the plugins we discussed
        baseUrl: "localhost/gatsby-wp/",
        protocol: "http",
        hostingWPCOM: false,
        // We will be using some advanced custom fields
        useACF: true,
        acfOptionPageIds: [],
        verboseOutput: false,
        perPage: 100,
        searchAndReplaceContentUrls: {
          sourceUrl: "http://localhost/gatsby-wp/",
          replacementUrl: "http://localhost:8000",
        },
        // Set how many simultaneous requests are sent at once.
        concurrentRequests: 10,
        includedRoutes: [
          "**/categories",
          "**/posts",
          "**/pages",
          "**/media",
          "**/tags",
          "**/taxonomies",
          "**/users",
        ],
        excludedRoutes: [],
        normalizer: function({ entities }) {
          return entities
        },
      },
    },

    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // 'gatsby-plugin-offline',
  ],
}

To test it works, restart gatsby develop and open localhost:8000/__graphql

Finish this React application and future plan

This is the last part of Create react app with GraphQL in WordPress

In this finishing part we build this application for production and plan for next development workflow.

Building application with the help of npm is pretty simple. Run

npm run build

and upload the files in build folder in server. You can see our application at reactblog.mrinalbd.com/. Also, can see the code if any need https://github.com/mrinal013/reactblog

Awesome experience to build this simple application. I heard some roar of Gatsbay. Within few days, I am going to build some stuff with Gatsbay with WordPress.

AppRouter setup with React, GraphQL, WordPress App

This is the second part of Create react app with GraphQL in WordPress

In this part, we will build src/AppRouter.js.


We will use { BrowserRouter, Route, Switch } from react-router-dom.
We will use ApolloClient and {gql} from apollo-boost package to connect React with Apollo. And import milligram CSS.
We will use App component here. Also, Post and NotFound component import here from respective file.

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import ApolloClient, { gql } from "apollo-boost";
import "milligram";
import App from './App';
import Post from './components/Post';
import NotFound from './components/NotFound';

We will use react-router-dom’s { BrowserRouter, Route, Switch } components here.

render() {
    return (
      <div className="container">
        <BrowserRouter>
          <Switch>
            <Route
              exact
              path="/"
              render={props => <App {...props} state={this.state.posts} />}
            />
            <Route
              path="/post/:postID"
              render={props => <Post {...props} state={this.state.posts} />}
            />
            <Route component={NotFound} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }

Here, the mechanism of Switch is like that,

  • When URL is root BrowserRouter render App component.
  • If URL is goes to single post BrowserRouter render Post component. Here :postID placeholder will be changed with real post id. Here, we render Post component with parent props and state.
  • If any user goes to other URL, BrowserRouter render NotFound component.

In AppRouter class, state is defined here. We can store data in state and use this state in different component.

state = {
  posts: []
},

At this point we will use componentDidMount life cycle. This life cycle is hooked when component mounted.

Here, we will use instance of ApolloClient class. ApolloClient class need uri which is https://mrinalbd.com/?graphql .

componentDidMount() {
  const client = new ApolloClient({
    uri: 'https://mrinalbd.com/?graphql'
  });
}

After defined client, we will run graphql query and then set posts in state. Let’s start dig in mud. Plan for now –
Step 1: ApolloClient’s instance client has query method. In this query we can use gql (graphql) which we imported at the start of this file.
Step 2: If this query successful then run a function. In this function we will write a command to store these data

Second, write the codes.

client
    .query({
      query: gql`
        {
          generalSettings {
              title
            }
          posts {
            edges {
              node {
                id
                title
                date
                link
                content
                excerpt
              }
            }
          }
        }
      `
    })
    .then(result => {
      this.setState({ posts: result.data.posts.edges });
    });

It is long code (for me). So break it down.
First we run a query to fetch data. This query is from official documentation of wpgraphql. https://docs.wpgraphql.com/getting-started/posts.
Second, run the promise of client. In this method we write an array function where result is parameter. This function command to state, let’s update. setState is recommended method to update state. And in this method update posts by post’s data, which we get from previous query.
So, Final code of src/AppRouter.js

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import ApolloClient, { gql } from "apollo-boost";
import App from "../App";
import Post from "./Post";
import NotFound from "./NotFound";

class AppRouter extends React.Component {
  state = {
    posts: []
  };

  componentDidMount() {
    const client = new ApolloClient({
      uri: "https://mrinalbd.com/?graphql"
    });
    client
      .query({
        query: gql`
          {
            posts {
              edges {
                node {
                  id
                  title
                  date
                  link
                  content
                  excerpt
                }
              }
            }
          }
        `
      })
      .then(result => {
        this.setState({ posts: result.data.posts.edges });
      });
  }
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" render={props => <App {...props} state={this.state.posts} />} />
          <Route
            path="/post/:postID"
            render={props => <Post {...props} state={this.state.posts} />}
          />
          <Route component={NotFound} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default AppRouter;

Setup for React front-end with GraphQL to Fetch WordPress back-end

This is first part of Create react app with GraphQL in WordPress

Download WP-GraphQL from https://github.com/wp-graphql/wp-graphql and rename it wp-graphql. Install it in WordPress and active this plugin as usual. Then, visit

domain.name/?graphql
WP-Graphql success message
wpgraphql success message

If it show a page of error, then confirmed wp-graphql plugin works.

Let’s create a brand new react app by

npx create-react-app apollographql

After npm finishes setup new react app. Go to apollographql project folder and start this app.

cd apollographql && npm start

We need to install three packages to use graphQL in React. Apollo makes possible to write query in GraphQL.

We will take a shot on small CSS framework https://milligram.io/ for quick style. We will also try styled components also. To checkout its advantage please see styled component’s motivation page.
To use pagination system in one page application we will use react-router. Also, for safe DOM render in react application we will use dompurify. Install these packages with this command. By default these packages install for development only.

npm i apollo-boost react-apollo graphql react-router-dom milligram styled-components dompurify

Here, i command is shorthand for install command. After these package installed, we have total 10 packages to use.

We will create some components. These are:

  • AppRouter
  • App
  • Posts
  • PostWidget
  • Post
  • NotFound

Open src/index.js, because it application start. Remove index.css and in App import. At last, use AppRouter in ReactDom. So the final code at src/index.js

import React from "react";
import ReactDOM from "react-dom";
import AppRouter from "./AppRouter";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(<AppRouter />, document.getElementById("root"));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

AppRouter component is defined App, Post and NotFound. App is mixed up with Posts and PostWidget.
Posts and a PostWidget componts will use in App component, Post component for single post and NotFound component for wrong URL enter in our application. Let’s, create these components.

First create a file in src named AppRouter.js. Be sure about naming convention. React follow camel casing for both filename and class name.
Open src/AppRouter.js. We know, for every react component we have to import React from react package. For first sight, we will define AppRouter in this file.

import React from "react";

class AppRouter extends React.Component {
  render() {
    return <div>Router</div>;
  }
}
export default AppRouter;

For this Application we will take advantage of ES6 and JSX. If you are interest about what does mean default export and named export, take a look on this.
Besides these package, we will also use five custom components.
Delete src/App.js. Create a folder components. In this folder, create App.js, Posts.js, PostWidget.js, Post.js, NotFound.js. Here, just declare component class for now.

Open src/components/App.js and write following code.

import React from "react";

class App extends React.Component {
  render() {
    return <div>App</div>;
  }
}
export default App;

Open src/Posts.js and write following code.

import React from "react";

class Posts extends React.Component {
  render() {
    return <div>Post Archive</div>;
  }
}
export default Posts;

Open src/components/Post.js and write following code.

import React from "react";

class Post extends React.Component {
  render() {
    return <div>Single Post</div>;
  }
}
export default Post;

Open src/components/PostWidget.js and write following code.

import React from "react";

class PostWidget extends React.Component {
  render() {
    return <div>Post Widget</div>;
  }
}
export default PostWidget;

Open src/components/NotFound.js and write following code.

import React from "react";

class NotFound extends React.Component {
  render() {
    return <div>Not Found!!!</div>;
  }
}
export default NotFound;

Create react app with GraphQL in WordPress

I am not going to compare REST vs GraphQL. As a silly Web developer, it is out of my boundary. If you are curious about this comparison, here are some good resources I found –

Also, GraphQL is topics in WordPress now-a-day.
https://kinsta.com/blog/wordpress-revolution-with-graphql/

You can find some other article about this tech war.

Anyhow, lets go to our main topics.
To make our journey a little easier, I will divide this development process in some parts.
Remember, I am writing these posts with share my development process. So, any part can be update in future part.
All posts are not completed yet. I am trying to complete all in next few days.