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;