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.

Post Component in React

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

In this part, we will mainly develop Post component for out application. But, before dive in main part, we will develop Loading component for see landing or search status in our application. Let’s dive in Loading component development.

Create a file named styled.js in components directory. In this file first import styled and keyframes class from styled-components package. Styled class is familiar to us. It helps us to style component efficient way. Beside, keyframes helper class will help us to develop animation. Keyframes in this package works as CSS3 @keyframes rule.

import styled, { keyframes } from "styled-components";

Then, assign styled in a exported constant named LoadingState. In this constant first declare some general properties and in after psuedo element define animation-name loading in special way. So, create a constant variable named loading. In this variable, we use keyframes and define animation as usual. Finally, styled.js is look like this

import styled, { keyframes } from "styled-components";

const loading = keyframes`
    from {
      transform: scale(1);
    }
    to {
      transform: scale(1.5);
    }
`;

const LoadingState = styled.div`
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  &:after {
    content: "";
    position: absolute;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #dedede;
    opacity: 0.4;
    animation: ${loading} 1s linear 0.1s infinite alternate;
  }
`;

export default LoadingState;

Now, we can import LoadingState both in App.js and Post.js. Awesome way to reuse.
Open src/components/App.js and delete styled-component import lines and related code. Just import LoadingState from styled.js file and use it second return in render method. Now src/components/App.js looks like this-

import React from "react";
import styled from "styled-components";
import Posts from "./Posts";
import PostWidget from "./PostWidget";
import LoadingState from "./styled";

const Widget = styled.div`
  border: 1px solid gray;
  padding: 10px;
  p {
    margin-bottom: 0;
    border-top: 1px solid gray;
    }
  }
`;

class App extends React.Component {
  render() {
    if (this.props.state.length) {
      return (
        <div className="row">
          <div className="column column-80">
            {this.props.state.map(post => (
              <Posts key={post.node.id} post={post} />
            ))}
          </div>
          <div className="column column-20">
            <Widget>
              <h3>Recent posts</h3>
              {this.props.state.slice(0, 2).map(post => (
                <PostWidget key={post.node.id} post={post} />
              ))}
            </Widget>
          </div>
        </div>
      );
    }
    return <LoadingState>Loading...</LoadingState>;
  }
}
export default App;

Let’s dive in Post component development.

Post component development

Open src/components/post.js. First import React from react package, Dompurify from dompurify package and LoadingState from styled.js which we developed just.

import React from "react";
import DOMPurify from "dompurify";
import LoadingState from "./styled";

Then, in our Post’s render method, we have to write a little bit complex (for me) code block.

  • Check component have state in its props.
  • During the checking time render LoadingState component.
  • Get post ID from props match object.
  • Loop every state and check this node id is equal to post id.
  • If found, store this state objecte in a predefined variable postInfo.
  • If not found, just render Post Not Found
  • When postInfo found, return post tiltle, body in defined format.

In code, this algorithm will be,

if (this.props.state.length) {
      let postInfo = {};
      const state = this.props.state;
      const postID = this.props.match.params.postID;
      state.forEach(function(post, index) {
        if (post.node.id === postID) {
          postInfo = post;
        }
      });
      if (postInfo.node) {
        return (
          <div className="column">
            <h2
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(postInfo.node.title)
              }}
            />
            <p
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(postInfo.node.content)
              }}
            />
          </div>
        );
      } else {
        return <div>Post Not Found</div>;
      }
    }
    return <LoadingState>Searching...</LoadingState>;

So, final code of src/component/post.js

import React from "react";
import DOMPurify from "dompurify";
import LoadingState from "./styled";

class Post extends React.Component {
  render() {
    if (this.props.state.length) {
      let postInfo = {};
      const state = this.props.state;
      const postID = this.props.match.params.postID;
      state.forEach(function(post, index) {
        if (post.node.id === postID) {
          postInfo = post;
        }
      });
      if (postInfo.node) {
        return (
          <div className="column">
            <h2
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(postInfo.node.title)
              }}
            />
            <p
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(postInfo.node.content)
              }}
            />
          </div>
        );
      } else {
        return <div>Post Not Found</div>;
      }
    }
    return <LoadingState>Searching...</LoadingState>;
  }
}
export default Post;

PostWidget component in React

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

In this part we will develop PostWidget component and a small edit of src/components/AppRouter.js

First small tweek of AppRouter.js

  • First import milligram in AppRouter to use in everywhere.
  • We will use a common component in header area of our application. Create src/components/Header.js
  • Update state to store title
state = {
  title: "",
  posts: []
};
  • Update query to fetch Blog title
client
      .query({
        query: gql`
          {
            generalSettings {
              title
            }
            posts {
              edges {
                node {
                  id
                  title
                  date
                  link
                  content
                  excerpt
                }
              }
            }
          }
        `
      })
      .then(result => {
        this.setState({
          posts: result.data.posts.edges,
          title: result.data.generalSettings.title
        });
      });
  • Add title props in render method of AppRouter.
      <div className="container">
        <BrowserRouter>
          <Header title={this.state.title} />
          <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>

So, now AppRouter.js file will

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

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

  componentDidMount() {
    const client = new ApolloClient({
      uri: "https://mrinalbd.com/?graphql"
    });
    client
      .query({
        query: gql`
          {
            generalSettings {
              title
            }
            posts {
              edges {
                node {
                  id
                  title
                  date
                  link
                  content
                  excerpt
                }
              }
            }
          }
        `
      })
      .then(result => {
        this.setState({
          posts: result.data.posts.edges,
          title: result.data.generalSettings.title
        });
      });
  }
  render() {
    return (
      <div className="container">
        <BrowserRouter>
          <Header title={this.state.title} />
          <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>
    );
  }
}

export default AppRouter

Develop Header Component
In src/components/Header.js

import React from "react";
import { Link } from "react-router-dom";

class Header extends React.Component {
  render() {
    return (
      <div>
        <Link to="/">
          <h1>{this.props.title}</h1>
        </Link>
      </div>
    );
  }
}
export default Header;

Develop PostWidget
Let’s open src/components/PostWidget.js.
First import { Link } and DomPurify

import { Link } from "react-router-dom";
import DOMPurify from "dompurify";

Then, render the title in link wrapper like this

<div>
  <Link to={`/post/${this.props.post.node.id}`}>
    <p
    dangerouslySetInnerHTML={{
    __html: DOMPurify.sanitize(this.props.post.node.title)
    }}
    />
  </Link>
</div>

So, full code of src/components/PostWidget.js is

import React from "react";
import { Link } from "react-router-dom";
import DOMPurify from "dompurify";

class PostWidget extends React.Component {
  render() {
    return (
      <div>
        <Link to={`/post/${this.props.post.node.id}`}>
          <p
            dangerouslySetInnerHTML={{
              __html: DOMPurify.sanitize(this.props.post.node.title)
            }}
          />
        </Link>
      </div>
    );
  }
}
export default PostWidget;

At last of this our application will be

Posts component in React

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

In this part, we will develop Posts component lives at src/components/Posts.js

First, we import Link component from react-router-dom and dompurify

import { Link } from "react-router-dom";
import DOMPurify from "dompurify";

In Posts component, first declare excerpt as

excerpt = this.props.post.node.excerpt;

Now, in return we create a link. Link component of react-router-dom creates link.

<Link to={`/post/${this.props.post.node.id}`}>
  <h2
    dangerouslySetInnerHTML={{
      __html: DOMPurify.sanitize(this.props.post.node.title)
    }}
  />
</Link>

Then render excerpt as

<article>
  <p
  dangerouslySetInnerHTML={{
    __html: DOMPurify.sanitize(
       this.excerpt.slice(0, this.excerpt.indexOf("Continue reading"))
    )
  }}
  />
</article>

Finally, src/components/Posts.js full codes are

import React from "react";
import { Link } from "react-router-dom";
import DOMPurify from "dompurify";

class Posts extends React.Component {
  excerpt = this.props.post.node.excerpt;

  render() {
    return (
      <div>
        <Link to={`/post/${this.props.post.node.id}`}>
          <h2
            dangerouslySetInnerHTML={{
              __html: DOMPurify.sanitize(this.props.post.node.title)
            }}
          />
        </Link>
        <article>
          <p
            dangerouslySetInnerHTML={{
              __html: DOMPurify.sanitize(
                this.excerpt.slice(0, this.excerpt.indexOf("Continue reading"))
              )
            }}
          />
        </article>
      </div>
    );
  }
}
export default Posts;

At now, our app is like this

App Component in React

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

In this part, we will build App component in src/components/App.js

Here kick on styled-components. And we use Posts and PostWidget component here. For that, we can introduce with props.

First, import CSS library, styled-componets. After that, we will import two components- Posts and PostWidget component from respective file. So, let’s write

import styled from "styled-components";
import Posts from "./components/Posts";
import PostWidget from "./components/PostWidget";

In App component, we will use render method. Here, return our defined JSX. Firstly, we design as simple. Two area in page. Details of grid can find here, https://milligram.io/#grids. So, we write here,

render() {
    return(
        <div className="row">
          <div className="column column-80">Post Archive</div>
          <div className="column column-20">Widget</div>
        </div>
    );
  }

At our App component, we will use two return. One return is used before state has any post. After return it return main component. So, our render function will be,

render() {
   if (this.props.state.length) {
    return(
        <div className="row">
          <div className="column column-80">Post Archive</div>
          <div className="column column-20">Widget</div>
        </div>
    );
  }
  return <p>Loading...</p>;
  }

At post archive, we will use posts array of state of this component. posts array map every items with render Posts. We render Posts component with props name state in this map. For clear about array map, we will read this.

However, in code it will be

{this.props.state.map(post => (
  <Posts key={post.node.id} post={post} />
))}

At Widget, we use same code. But, before array map, we will slice this array for that only first two posts render here. In code

{this.props.state.slice(0, 2).map(post => (
  <PostWidget key={post.node.id} post={post} />
))}

Lets, try styled-components.
Define Widget with styled. styled create an div tag and it styled as our defined style.

const Widget = styled.div`
  border: 1px solid gray;
  padding: 10px;
  p {
    margin-bottom: 0;
    border-top: 1px solid gray;
    }
  }
`;

Use this Widget component like this

<Widget>
   <h3>Recent posts</h3>
     {this.props.state.slice(0, 2).map(post => (
       <PostWidget key={post.node.id} post={post} />
     ))}
</Widget>

So, the final code is-

import React from "react";
import styled from "styled-components";
import Posts from "./Posts";
import PostWidget from "./PostWidget";

const Widget = styled.div`
  border: 1px solid gray;
  padding: 10px;
  p {
    margin-bottom: 0;
    border-top: 1px solid gray;
    }
  }
`;

class App extends React.Component {
  render() {
    if (this.props.state.length) {
      return (
          <div className="row">
            <div className="column column-80">
              {this.props.state.map(post => (
                <Posts key={post.node.id} post={post} />
              ))}
            </div>
            <div className="column column-20">
              <Widget>
                <h3>Recent posts</h3>
                {this.props.state.slice(0, 2).map(post => (
                  <PostWidget key={post.node.id} post={post} />
                ))}
              </Widget>
            </div>
          </div>
      );
    }
    return <div>Loading...</div>;
  }
}
export default App;

Screenshot at this point will be

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.

Create a react application with WordPress Rest API

Assume, create-react-app installed. Otherwise, follow https://mrinalbd.com/start-adventure-with-react/

Install brand new app with bash command.

npx create-react-app mrinalreact

Then, change directory and npm start with following command

cd mrinalreact && npm start

App will start at http://localhost:3000/

We can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window.fetch. I use Axios for this application. Install axios with npm by typing command

npm install axios

Let’s open src/index.js, Here, ReactDom render App class at document element which ID root. This root element lives in our output page public/index.html.

Let’s open src/App.js. Delete all line. We will build this and know how this small peace worked. Deleting all lines will produce a error on browser.
Why does it happen? Because, this app going its journey from public/index.html ‘s id root. But, our app can’t have a class or function App.

For this post we will develop only one file-src/App.js. Open it and import React and Axios from respective packages at first.

import React from "react";
import axios from "axios";


Be careful about type React and axios name.React is capitalize and axios is lowercase.

Define App class by extending React’s Component class. Don’t forget to export default App class. In react class or function is export in two ways-Named and Default. I will discuss about these on another post.

class App extends React.Component {

}
export default App;


React.Component have a function named render() which return anything we write here. For our application, we use this render() to show output. Let’s output a list of dummy posts title.

import React from "react";
import axios from "axios";

class App extends React.Component {
 render() {
   return (
    <div>
      <ul>
        <li>First post</li>
        <li>Second post</li>
        <li>Third post</li>
      </ul>
    </div>
   );
 }
}
export default App;

It show ordinary and boring dummy title list as

static list

To store all posts in our application, let’s create a store in App class. Here, posts array will store all posts.

  state = {
    posts: []
  };

I will fetch all posts from this WordPress site with axios get method. All posts live at https://mrinalbd.com/wp-json/wp/v2/posts.

At react, there are several life cycle hook available. Posts will fetch by axios when this component mounted. So, we will use componentDidMount().

At componentDisMount(), axios will fetch data from https://mrinalbd.com/wp-json/wp/v2/posts. If this fetching success, then axios promise to run a function. To write this function, I will use array function style. In this function we will get posts from response data and set it in our state’s posts array. setState() is special method to update state.

componentDidMount() {
    axios.get("https://mrinalbd.com/wp-json/wp/v2/posts").then(response => {
      const posts = response.data;
      this.setState({ posts });
    });
  }

Finally, we will show it in our boring list. In Javascript, array elements can map. But, we can’t map object. So, this posts array can map with a function where post title is rendered in list style.

{this.state.posts.map(post => (
    <li>{post.title.rendered}</li>
))}
react post list

As post will grow this list will grow. So, my final code of src/App.js

import React from "react";
import axios from "axios";

class App extends React.Component {
  state = {
    posts: []
  };
  componentDidMount() {
    axios.get("https://mrinalbd.com/wp-json/wp/v2/posts").then(response => {
      const posts = response.data;
      this.setState({ posts });
    });
  }
  render() {
    return (
      <div>
        <ul>
          {this.state.posts.map(post => (
            <li>{post.title.rendered}</li>
          ))}
        </ul>
      </div>
    );
  }
}
export default App;