View Categories

How to Build WordPress Apps With Frontity (In 5 Steps)

A child building with blocks.
  • Sep 24, 2020
  • 0
  • by A2 Dev Team

Traditionally, WordPress development has been centered around PHP.  While this is a robust language that has proven reliable over the years, having multiple options gives you greater choice. If you’re a React developer looking for the right framework for WordPress, there are many reasons to try out Frontity.

Frontity is a free and open-source framework that helps you build WordPress applications using React JS. Although React development offers a lot of benefits, you would normally have to follow a complex setup process that includes bundling, server rendering, etc. Fortunately, Frontity eliminates all of these procedures, and gets you to the development stage in no time.

In this article, we’ll walk you through the process of building a web application with Frontity. Before that, let’s consider why Frontity is a great option for your WordPress project. Let’s get started!

What Frontity Is and Why It’s Great for Building Web Applications

The Frontity web application.

Frontity is a framework that enables you to build a React-based front-end for a headless WordPress website. Once Frontity is set up, your WordPress website will serve its data via the REST API. Frontity will then consume this data, and render it in the web browser as a Single Page Application (SPA).

Instead of the visitor browsing from one page to the next, a SPA dynamically rewrites the same page with new data that it retrieves from the server. You can host Frontity on either a regular Node.js server or in a serverless environment.

Although it’s possible to build a headless website without using tools such as Frontity, this usually requires you to manage a list of tasks. These tasks include transpiling, routing, server rendering, retrieving data from WordPress, and much more.

While you could reduce the workload using a framework such as Next.js or Gatsby.js, these solutions aren’t designed specifically for WordPress. To use them with WordPress, you would need to perform a significant amount of configuration. You might also have to install some additional tools.

By contrast, Frontity was designed with WordPress firmly in mind. Every part of the Frontity framework has been simplified and optimized specifically for the platform. Frontity also includes everything you need to develop for WordPress, including React, TypeScript, CSS-in-JS and Babel. Since you don’t have to set up additional tooling, you’re free to concentrate on what really matters: building your website.

Frontity can also improve your website’s performance, resulting in fast loading times with no extra assets or round-trips required. It responds to requests with a fully-populated HTML file generated with React, which reduces the time required for the first contentful paint. Once React has loaded, Frontity’s router prefetches other routes and data automatically.

In other words, your visitors should never have to wait while navigating your site. Since page speed is a ranking factor for Google searches, using an optimized solution such as Frontity can also deliver a significant SEO boost.

Last but not least, Frontity is designed to be extensible, with its team already working on extensions for Yoast SEO, AdSense, SmartAds, and Google Analytics. These extensions aren’t currently available, but Frontity has created a GitHub page where the finished extensions will be posted. Frontity’s themes are also compatible with the React packages that are currently available via the Node Package Manager (NPM).

How to Build a Web Application Using Frontity (In 5 Steps)

To build a web application using Frontity, you’ll need a WordPress installation. It can be hosted on a web server or locally.

We’ll also be using Node.js to run Frontity commands. To see whether you already have Node.JS installed, you can open a Terminal on your computer and run the following command:

node -v

If the Terminal returns a version number, then Node.js is already installed. If not, you can install Node.js from the official site.

Step 1: Launch a New Frontity Project

The first step is creating a local Frontity project, and then connecting this project to your WordPress installation. To do this, open a Terminal and run the following command:

npx frontity create my-project

You’ll need to replace my-project with the name of your project. Frontity will then ask you to select either the Mars or the TwentyTwenty theme. If you’re new to Frontity, then it’s recommended that you select Mars.

Once you’ve made your selection, Frontity will clone your chosen theme, create all the necessary files, and install any required dependencies. You can also specify whether you want to receive Frontity updates via email.

After a few moments, you should see a Frontity project created message. Frontity has now created a directory on your local machine, with the project name you specified. By default, Frontity projects are stored in your users directory:

Frontity projects.
This directory contains the following important Frontity files and folders:

  • Frontity.settings.js. This is where you’ll define your project’s settings and any packages it requires.
    Node_modules. This is where all of your dependencies are stored. You shouldn’t need to modify any of the files contained within this folder.
    Package.json. This is used to configure your Node.js project, and is also where you’ll store the dependencies required by your application.
    Packages. This folder contains all your local packages, including your theme.

Next, change directory (cd) so that the Terminal is pointing at the project’s root directory, for example:

cd /users/my-project

You can now start development by running the following command:

npx frontity dev

Once you run this command, a new page should open automatically in your default web browser. Initially, Frontity will connect to a test blog that displays demo content:

Demo content.

You can connect Frontity to your own WordPress website by editing the frontity.settings.js file inside your project directory.

You should be able to open this file using any text editor. The contents should look something like this:

const settings = {
  "name": "my-project",
  "state": {
    "frontity": {
      "url": "https://test.frontity.org",
      "title": "Test Frontity Blog",
       description": "WordPress installation for Frontity development"
    }
  },
  "packages": [
    {
      "name": "@frontity/mars-theme",
      "state": {
        "theme": {
         "menu": [
            [
              "Home",
              "/"
            ],
            [
              "Nature",
              "/category/nature/"
            ],
            [
              "Travel",
              "/category/travel/"
            ],
            [
              "Japan",
              "/tag/japan/"
            ],
            [
              "About Us",
              "/about-us/"
            ]
            ],
          "featured": {
            "showOnList": false,
            "showOnPost": false
          }
        }
      }
    },
    {
      "name": "@frontity/wp-source",
      "state": {
        "source": {
          "api": "https://test.frontity.org/wp-json"
        }
      }
    },
    "@frontity/tiny-router",
    "@frontity/html2react"
  ]
};

In this file, find the api property. By default, this property is set to https://test.frontity.org/wp-json. You’ll need to change this to the address of your own website, with the wp-json extension. For example, if your website is https://example.com, then you should enter https://example.com/wp-json:

     "name": "@frontity/wp-source",
      "state": {
        "source": {
          "api": "https://example.com/wp-json"
        }
      }
    },

Save your changes, and refresh the Frontity tab in your web browser. This page should update to display content pulled directly from your own blog.

Step 2: Add Pages to Your App

Frontity is now connected to your website, but the menu still contains links to Frontity’s demo content (Nature, Travel, Japan, and About Us). If visitors click on any of these links, then they’ll encounter a 404 error:

A 404 error.

You need to replace these placeholder pages with your own content. In your local project directory, open the frontity.settings.js file, and find the packages section. It should look something like this:

 "packages": [
     {
       "name": "@frontity/mars-theme",
       "state": {
         "theme": {
           "menu": [
             [
               "Home",
               "/"
             ],
             [
               "Nature",
               "/category/nature/"
             ],
             [
               "Travel",
               "/category/travel/"
             ],
             [
               "Japan",
               "/tag/japan/"
             ],
             [
               "About Us",
               "/about-us/"
             ]
           ],

You can now replace these placeholders with your own pages. For example, if you wanted to link to your website’s Store page, located at https://example.com/store, then you’d use the following:

 "packages": [
    {
      "name": "@frontity/mars-theme",
       "state": {
         "theme": {
           "menu": [
             [
               "Store",
                  "/store/"
            ],
....
....
….
            ]
          ],

If you wanted to link to your hat product, located at https://example.com/store/hat, then you’d add the following:

 "packages": [
    {
      "name": "@frontity/mars-theme",
      "state": {
        "theme": {
          "menu": [
            [
              "Hat",
                 "/store/hat/"
            ],
...
...
...
            ]
         ],

As an example, we’re going to add the following pages to the Frontity menu: Home, Store, About Us, and Contact Us:

  "packages": [
    {
      "name": "@frontity/mars-theme",
      "state": {
        "theme": {
          "menu": [
           [
             "Home",
              "/"
           ],
           [
              "Store",
              "/store/"
           ],
           [
              "About Us",
               "/about-us/"
           ],
           [
              "Contact Us",
              "/contact-us/"
           ]
           ],

You can now save these changes. Refresh your website, and the menu should update with links to all of your pages.

Step 3: Customize Your Theme

When you set up Frontity, you selected either the Mars or the TwentyTwenty theme. This theme controls your site’s appearance, but you can modify the default look by editing it at the code level.

By customizing the various files that make up your chosen theme, you can add new User Interface (UI) elements, remove elements, add padding and margins, and make countless other stylistic changes.

To make these customizations, you’ll need to edit the contents of your project’s packages/theme-name folder. For example, if you’re using the Mars theme, then the packages folder contains a mars-theme directory:

A macOS Finder window, displaying the Mars theme package.

In this directory, you can change various onscreen elements. To illustrate the general process, we’ll be changing the color of our website’s title text using HTML.

In HTML, colors are defined using Red-Green-Blue (RGB) values, Hexadecimal (HEX) values, Hue-Saturation-Lightness (HSL) values, Red-Green-Blue-Alpha (RGBA) values, or Hue-Saturation-Lightness-and-Alpha (HSLA) values. You can quickly and easily generate a code using a color picker such as HTML Color Codes.

To make this change, navigate to packages/mars-theme/src/components. Open the header.js file in your text editor, and then find the following section:

const Container = styled.div`
  width: 848px;
  max-width: 100%;
  box-sizing: border-box;
  padding: 24px;
  color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
`;

The #fff attribute is the code for white:

White header text.

You can change the color of this text by replacing color #fff with a different HTML color code. In the following snippet, we’re styling this text so that it appears black:

const Container = styled.div`
  width: 848px;
  max-width: 100%;
  box-sizing: border-box;
  padding: 24px;

//Change the following line//

  color: #000000;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
`;

When we save our changes, the new color is immediately applied to the header text:

The Mars theme, with customized header text.

It’s well worth spending some time exploring the various theme files and folders, to see what changes you can make. With a few code-level tweaks, you can put a unique spin on any theme, and help your website stand out from the crowd.

Step 4: Add Extra Features to Your App

Disqus is a blog comment hosting service. WordPress may support comments out-of-the-box, but Disqus can provide some additional benefits, including social network integration, advanced administrative and moderation options, and native ads that you can place around your comments section:

A Disqus comments section.

Once you’ve installed and imported Disqus into your local project, you can add a related comments section to any part of your site. We’ll show you how to add one to every single post that appears across your website.

To start, you’ll need to install Disqus. You can do this by running a command in your Terminal:

npm install disqus-react

Next, you need to implement Disqus as a component. We’d recommend creating a standard Frontity component directory structure.

In the comments.js file, add the following:

import React from "react";
import { connect } from "frontity";
import Disqus from 'disqus-react';

const Comments = ({ state }) => {
    const data = state.source.get(state.router.link);
    const post = state.source[data.type][data.id];

    const disqusShortname = “blog-name”;

     const threadConfig = {
          url: `https://${disqusShortname}.com${state.router.link}`,
          identifier: post.id,
          title: post.title.rendered,
   };

    return (
      <Disqus.DiscussionEmbed shortname={disqusShortname} config={threadConfig} />
    )
}
export default connect(Comments);

Next, you’ll need to implement Disqus through namespaces. In your index.js file, add the following:

import Comment from "./comment";

export default {
    libraries: {
        comments: {
            Comment
         }
    }
};

Since we want comments to appear on all posts, we’ll need to open Frontity’s post.js file. If you’re using the Mars theme, this is located in packages/mars-theme/src/components.

Open this file for editing, and find the following section:

      {/* Render the content using the Html2React component so the HTML is processedby the processors we included in the libraries.html2react.processors array. */}
      <Content>
        <Html2React html={post.content.rendered} />
      </Content>
    </Container>
  ) : null;
};

You should update this section to reference the comments package you just created:

       {/* Render the content using the Html2React component so the HTML is processedby the processors we included in the libraries.html2react.processors array. */}
        <Content>
            <Html2React html={post.content.rendered} />
  <libraries.comments.Comments />
       </Content>
     </Container>
  ) : null;
};

Save your changes, and refresh your blog in the web browser. If you open any post and scroll to the bottom, it should now feature a Disqus comment section.

Step 5: Publish Your App

Once you’re happy with your Frontity web application, you can deploy it to production. To create a production-ready bundle, run the following command from the root of your project:

npx frontity build

This will create a build folder containing your React application and Frontity (Node.js) server. You’ll find this folder in your project’s root directory:

A project root directory.

You can deploy this folder to any hosting that’s capable of serving a Node.js application. For example, you can use npx frontity serve to run your project like a standard Node.js application, or upload it to a Content Delivery Network (CDN) and serverless service.

Frontity recommends Vercel as a serverless solution, although you could also use AWS Lambda, Netlify or Google Functions. To deploy your Frontity app using Vercel, you need to create a Vercel account. In your Terminal, run the following command:

npx vercel login

When prompted, enter your email address. Vercel will now send a Verification email to your account; open this email and give the Verify button a click.

On your computer, open your Frontity app’s root directory. Then create a vercel.json file containing the following:

{
  "version": 2,
  "builds": [
     {
       "src": "package.json",
       "use": "@frontity/now"
     }
  ]
}

Save this file, and run the following Terminal command:

npx vercel

After a few moments, the Terminal should ask whether you want to set up and deploy your project. To deploy, press the y key, followed by Enter .

You can now choose the scope that you want to deploy to, and whether you’re deploying to an existing project. If you deploy to a new project, then you can give that project a name. Note that Vercel only supports hyphens, lowercase letters, and numbers. You’ll also need to specify the local directory where your project is located.

Once you’ve entered this information, Vercel will assign your project a live URL, in the format https://example.vercel.app. Vercel also generates a project settings URL, in the format https://vercel.com/vercel-username/my-frontity-project/settings. This URL opens your project’s settings in the Vercel console.

The Vercel "Project Settings" screen.

Here, you can make various changes to your project, including assigning new domains to your deployment, and integrating Vercel with Git so that changes are pushed to your Git repositories automatically.

Conclusion

There’s no doubt that Frontity makes WordPress-React development easier. This framework helps you to create apps that are SEO-friendly, possess great designs, and perform well. By creating a web application using Frontity, you can reduce the workload and configuration typically required to create a headless WordPress website.

Here’s a quick recap of the steps involved in building a web application using Frontity:

  1. Launch a new Frontity project.
  2. Add pages to your app.
  3. Customize your theme.
  4. Add extra features to your app.
  5. Publish your app.

Once you’re happy with your web application, you can host it in a serverless environment or opt for developer-friendly web hosting that’s optimized for Node.js!

Image credit: FeeLoona.

The A2 Posting