Blog posts under the React tag https://webdevstudios.com/tags/react/ WordPress Design and Development Agency Tue, 09 Jul 2024 21:07:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the React tag https://webdevstudios.com/tags/react/ 32 32 58379230 Debugging React with VS Code and Chrome https://webdevstudios.com/2023/07/06/debugging-react-with-vs-code-and-chrome/ https://webdevstudios.com/2023/07/06/debugging-react-with-vs-code-and-chrome/#comments Thu, 06 Jul 2023 16:00:03 +0000 https://webdevstudios.com/?p=26056 Have you ever considered using a debugger for your React project but decided to keep on using console.log() instead because you thought it would be a pain to set up proper debugging? I did, until one day, I needed to get into the weeds on a project, and I figured I’d try and set up Read More Debugging React with VS Code and Chrome

The post Debugging React with VS Code and Chrome appeared first on WebDevStudios.

]]>
Have you ever considered using a debugger for your React project but decided to keep on using console.log() instead because you thought it would be a pain to set up proper debugging?

I did, until one day, I needed to get into the weeds on a project, and I figured I’d try and set up debugging in hopes of making my life easier. I was delighted to find out how easy it was! In this post, I’ll demonstrate how to debug a React project using VS Code and Chrome.

To demonstrate how to set things up, I’m going to use Vite and React to set up a React project. You’ll need to have VS Code and NPM installed.

Set Up a Workspace in VS Code

First, create a directory for our workspace. Then Open the directory in VS Code. Save the workspace.

I used D:devtrainingdebugging-react.

Create a React Starter Project Using Vite

From VS Code, open up this location in the integrated terminal and run the following command to create a starter project: npm create vite@latest

Create a Vite project

Follow the prompt from Vite. Give the project a name (I used vite-demo ). Select React for the framework and JavaScript for the variant.

Once that’s all set, change directories into the project folder that you assigned, run npm install.

Install packages

Once the installation is complete, start Vite by running npm run dev.

Run Vite

We can see that our project is running on localhost, port 5173. A browser window will be opened with the project:

Vite + React demo page

Create and Configure a launch.json File in VS Code

Now we need to create a launch.json file. Click the Debug icon (1), then create a launch.json file (2). The launch.json file will be located in your workspace’s .vscode directory.

Create launch.json file

Select the location:

Select the location

Select Chrome for the debugging type:

Debugging type: Chrome

This will open the launch.json file in a tab. (1) Set the port to whatever was specified by Vite earlier (5173 by default), and (2) add the subdirectory your project is into the webRoot option if you have your project in a subdirectory like I do here (/vite-demo).

Configure launch.json file in VS Code

Add a Breakpoint to the Code

Now open up your project’s src/App.jsxfile (1) and (2) add a breakpoint to line 20. We’re going to debug the count variable.

Add a breakpoint

Start Debugging Your React Project!

OK, we’re getting close! Now click the Start button to start debugging. This will launch our app in a new Chrome window.

Start debugging

The app is paused for debugging.

App opened for debugging in Chrome

A debugging session is now active in VS Code. We can use the debugging control bar to step through and inspect the code.

Debugging session is now active

We can interact with the app and see the value of the counter increase after clicking the count button.

Click the counter

Observe counter value

Here’s a quick screen capture showing this in action:

Debugging screen capture

One thing to note is that, by default, React.StrictMode is enabled in dev mode, so your app will be run twice. See the docs for details on Strict Mode.

That’s all there is to setting up basic React debugging in VS Code and Chrome. I hope this helps you to more efficiently debug your React projects.


Are you struggling with WordPress security? Our free guide teaches you everything you need to know to protect your site. Download and read our “Guide to WordPress Security” to safeguard your website.

The post Debugging React with VS Code and Chrome appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2023/07/06/debugging-react-with-vs-code-and-chrome/feed/ 1 26056
Creating Your First Remix App https://webdevstudios.com/2022/06/14/creating-your-first-remix-app/ https://webdevstudios.com/2022/06/14/creating-your-first-remix-app/#respond Tue, 14 Jun 2022 16:00:47 +0000 https://webdevstudios.com/?p=24947 Keeping up with JavaScript is not difficult. If you are still new to Remix, the web framework, and would like to try it, then this article is for you! Why Not Remix? Every day, we see new changes and improvements in the JavaScript ecosystem. Remix gained popularity with the hype from top website agencies and Read More Creating Your First Remix App

The post Creating Your First Remix App appeared first on WebDevStudios.

]]>
Keeping up with JavaScript is not difficult. If you are still new to Remix, the web framework, and would like to try it, then this article is for you!

Why Not Remix?

Every day, we see new changes and improvements in the JavaScript ecosystem. Remix gained popularity with the hype from top website agencies and developers.

Is it worth the hype? Give it a try and you can conclude for yourself.

With in-built hooks and components, Remix makes it easy to fetch data, create dynamic routes, use forms and handle errors. It also comes with HTTP helpers to get responses in JSON and to redirect.

Remix offers only server-side rendering and that makes it different from Next.js. In this example, we will build a simple application that displays a list of posts from a WordPress blog and has a details page and a comments form.

Remix WP app demo

I assume you are a React developer and used some other React-based frameworks like Next.js. This is not a step-by-step tutorial, yet covers the points that you will like to try and explore. Here is the repository for this demo if you like to see the code first.

Installation

Prerequisites

Start the installation by running the commands. This will ask you a series of questions that allows you to choose the location, typescript, and app server.

View the code on Gist.

This is the last step of the installation; you will get a message like:

That’s it! `cd` into "/Users/lax/local/remixwp" and check the README for development and deploy instructions!

README file contains more detailed information about the commands.

Folder Structure

  • app – This is like the src/ folder in create-react-app (CRA), where the components of our app are located.
  • node_modules
  • public – A folder for static files like images and other public assets
  • .gitignore
  • jsconfig.json – A configuration file for the compiler
  • package – lock.json and package.json
  • Remix.config.js – Remix configuration file; keep the default config

Let’s start the development. Change your working directory to Remix-wp or the folder where you installed the app and run:

npm run dev

If any app is running on the default port 3000, Remix will increment the port number. In my case, my app started on port 3002 since I have 2 other apps running.

This index page is clean and easy to get started with bare minimal code. I chose just the basics for this demo without using any predefined templates.

Remix comes with a jokes app and a developer blog app example. You can install them and take a quick look.

App folder

The app is the heart of the application. Let’s see what it contains

  • routes – Remix supports file-based routing. The folders and files here control the routes.
  • entry.client.jsx – As the name suggests, this acts as the entry point for the client. HTML gets hydrated and added to DOM through this file.
  • entry.server.jsx – This runs only on the server side. This acts as the entry point to the server and generates the HTML and server response.
  • root – This file is equivalent to App.jsx of the CRA and the default component that loads first.

Tailwind

Install tailwind package.

npm install -D npm-run-all tailwindcss

Create Tailwind config file.

npx tailwindcss init

Update tailwind config and mention the files to be added.

content: ["./app/**/*.{ts,tsx,jsx,js}"],

Add the commands to scripts in package.json.

View the code on Gist.

Then, import tailwind on app/root.jsx.

View the code on Gist.

Add Document, Layout

As this app doesn’t contain a global document, layout, and error boundaries set. Let us add them to root.jsx.

This works similar to the Next.js Document file, where you load the child components and nest them to the main layout. Remix provides an outlet component that will render content according to routes. To keep the layout of the app uniform, let’s wrap the outlet component with a layout, which in turn is wrapped inside a document.

View the code on Gist.

Document will return the child components and the HTML markup, as described here.

View the code on Gist.

This is a simple layout that contains a header and footer.

View the code on Gist.

Setting up an error boundary is easy, as it comes out of the box with Remix. To keep things simple, I have added a console.log to check error messages on the log and also display them on the frontend.

View the code on Gist.

Components and Hooks

The header, footer, and comments form are the components of this app.

  • Link – Used to add hyperlinks
  • Form – Renders an HTML form and provides the submitted form data using the useActionData hook
  • useLoaderData – This hook is the Remix version of getServerSideProps in Next.js. This allows you to fetch data and make it available via the loader function.

Routes

It is no wonder that routes are easy in Remix, as it is created by the same people behind React Router. You don’t have to manually define each route. A folder or a dynamic route that has ‘$’ in the file name would be considered a route.

Fetching data

Posts/index.jsx file fetches data and lists them out using the loader function. Each post item is linked to its detail page using slug as the dynamic route.

useParams hook is used to access parameters on the dynamic route.

View the code on Gist.

Comment Form

Import the form component. You can intercept the form submission and validate each field. Then, process the submitted data.

As a PHP developer, I found the usage of forms with Remix so exciting.

You can set the form action and access the submitted data there. In this example, we have a comments form and display the raw submitted comments. You can extend this by sending data to the WordPress source and displaying the response.

Deployment

Deployment instructions will get added to the README file during installation. You can deploy this app as you would deploy any node app.

npm run build

Then run:

npm run start

Test your app locally. Choose a host of your choice. I used Vercel to deploy this app. Once you choose the repository, Vercel will automatically pick up the configuration for build commands and run.

Conclusion

There are a few areas that you can continue working on in this example:

  • Make the WordPress source URL an environment variable.
  • Add components for each post item in the posts list.
  • Add a frontend form to allow users to submit post content.
  • Add a terms route for tags or category archives.

And the list goes on!

I hope you find this quick overview of Remix helpful. Try it out and let us know what you think in the comments below.

The post Creating Your First Remix App appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/06/14/creating-your-first-remix-app/feed/ 0 24947
React for WordPress Developers https://webdevstudios.com/2022/01/11/react-for-wordpress-developers/ https://webdevstudios.com/2022/01/11/react-for-wordpress-developers/#respond Tue, 11 Jan 2022 17:00:43 +0000 https://webdevstudios.com/?p=24545 WordPress core uses React for the Gutenberg block editor, which means it is high time for every WordPress developer to learn and get familiar with React. Getting started with React can be tricky. Let this blog post help you. I started learning React a few months ago, as part of my professional goals at the Read More React for WordPress Developers

The post React for WordPress Developers appeared first on WebDevStudios.

]]>
WordPress core uses React for the Gutenberg block editor, which means it is high time for every WordPress developer to learn and get familiar with React. Getting started with React can be tricky. Let this blog post help you.

I started learning React a few months ago, as part of my professional goals at the WebDevStudios. With some hands-on experience with React, I can now understand and create Gutenberg blocks and learn other React-based frameworks, like Next.js.

Everyone has their preferred way of learning, yet the need for building something is paramount. Okay, so how do you get started? Are there any simple courses for beginners? Where do you deploy an app? All your questions are answered here.

Note these prerequisites: as a beginner, you need to understand JavaScript ESNext Syntax and new methods before getting started with React. As a starting point, read React’s official documentation. You can also look at example projects created by the React community.

What to Learn

Every other day, new React frameworks, packages, and tools are released or get updated. You don’t have to catch up with all of them at once.

React basics

Learn the basics well and then you can gradually advance further down the road.

  • JSX
  • Components
  • States and props
  • Routing

Courses

Below is a list of resources for any WordPress developer learning React.

Scrimba

This online course platform has a built-in editor while the video is playing. You can call this a combination of CodePen and Udemy.

While you are watching the video course, you can double click on the video. Ta-da! You have the code editor IDE to start editing code.

Scrimba

You can create folders, organize your files, add dependencies, and most importantly, you don’t have to stop watching the video. Scrimba has a free 11-hour React course for beginners. If you are interested in learning React without installing it on your computer, give it a try.

YouTube

When it comes to learning code, YouTube is a good place to start. You can filter based on your preferences, like long videos, crash courses, etc. Here are some suggested channels for learning React:

Egghead.io

Kent C. Dodds, one of the reputed names in the React world, has a great free community resource called the “Beginner’s Guide to React.” Egghead also has short and super-specific React tutorials for beginners.

Other Resources

Sal Ferrarello’s React Starters

WebDevStudios Principal Engineer, Sal Ferrarello, came up with starter projects for anyone who is learning React. Sal practices what he preaches, but the real learning comes when you start building something.

These starter projects are simple, arranged in the order of learning new topics, and easy to follow. What I really like about them is the ease of setting up the environment.

The projects are bundled with working solutions, which you have to complete and improvise. Most starter projects available on the internet are either fully completed code or just the idea with minimal or fewer directions.

If it’s completed code, you might just copy-paste it or just follow what is in there. And if it is just an idea, it might be daunting to a beginner to set up the project or have issues with installation.

Both these approaches are not effective in my opinion, as they miss the main objective of building something at the beginner level. This is where Sal’s starters are winning over others out there.

Each starter project asks you to come up with your own solution, but you don’t have to start from scratch.

Access Sal’s ReactJS starters at GitHub.

What is next?

Once you have learned and practiced the basics of React, now it’s time to build some Gutenberg blocks. You can also start building Headless CMS with WordPress and Next.js.

Are you just starting with React? Share your experiences below in the comments.

The post React for WordPress Developers appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/01/11/react-for-wordpress-developers/feed/ 0 24545
Headless WordPress with React and NextJS (Part 2) https://webdevstudios.com/2019/01/10/headless-wordpress-with-react-and-nextjs-2/ https://webdevstudios.com/2019/01/10/headless-wordpress-with-react-and-nextjs-2/#comments Thu, 10 Jan 2019 17:00:25 +0000 https://webdevstudios.com/?p=19398 Editor’s Note: The following is Part 2 in a two-part series titled, “Headless WordPress with React and NextJS.”  It was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current content on Headless CMS and Headless WordPress, click here. Visit the Read More Headless WordPress with React and NextJS (Part 2)

The post Headless WordPress with React and NextJS (Part 2) appeared first on WebDevStudios.

]]>
Editor’s Note: The following is Part 2 in a two-part series titled, “Headless WordPress with React and NextJS.”  It was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current content on Headless CMS and Headless WordPress, click here. Visit the WebDevStudios GitHub to access our Next.js WordPress Starter.

In Part 1 of this series, we set up a simple app to display our posts using React and Next.js alongside our WordPress install. We left it lacking some extra functionality that would take us from a simple test to a real browser-accepted website. So, let’s get to work on that and really round this thing out.

First up are single posts. We’re going to continue to work in our posts.js and get some links and such working first.

Our main update, like in Navigation.js, will be to import our Link component and wrap each of our post titles.

import Link from 'next/link'

and then

<li key={ post.id }>
    <Link href={ `/posts/${ post.slug }` }>
        <a href={ `/posts/${ post.slug }` }>
            { post.title.rendered }
        </a>
    </Link>
</li>

From here we have links, but they won’t go anywhere.

In fact, if you tried, you’d get the default 404 error from express.

Dynamic Routing

This is where things get a little complicated. Out of the box, Next.js handles direct routing, but dynamic routing is a little bit more complicated. You don’t want to have a component for each of those posts; you want one to handle them all. We’ll need a custom express server to serve the routes and handle all of that for us. Next.js is handling a lot of that for us already, but we’d still need a custom server for the dynamic routes. We could fully integrate React Router into the build, but we’re building something pretty simple here and that might be a bit of overkill.

I’ve decided to utilize a middleware for Next.js called next-routes alongside a custom server to make things a bit easier to understand and less complicated if only a little. So let’s install that:

$ npm install express next-routes --save

From there, let’s create a couple of new files at the root of your project named routes.js and a server.js.

In our routes file, we’ll just import next-routes and add our routes. In this case, we’ll have, as we’ve set up, our index, our posts page, and our new dynamic route for our single posts.

const routes = require( 'next-routes' );

// Setup router.
module.exports = routes()
  .add( 'index', '/' )
  .add( 'posts' )
  .add( 'single', '/posts/:slug' );

Inside our server is a little more complicated. We’ll end up with this:

const express = require( 'express' );
const next    = require( 'next' );

// Import middleware.
const routes = require( './routes' );

// Setup app.
const app     = next( { dev: 'production' !== process.env.NODE_ENV } );
const handle  = app.getRequestHandler();
const handler = routes.getRequestHandler( app );

app.prepare()
  .then( () => {

    // Create server.
    const server = express();

    // Use our handler for requests.
    server.use( handler );

    // Don't remove. Important for the server to work. Default route.
    server.get( '*', ( req, res ) => {
      return handle( req, res );
    } );

    // Get current port.
    const port = process.env.PORT || 8080;

    // Error check.
    server.listen( port, err => {
      if ( err ) {
        throw err;
      }

      // Where we starting, yo!
      console.log( `> Ready on port ${port}...` );
    } );
  } );

From the top:

  • Import express (our server environment) and next (important)
  • Import our new route file, our middleware
  • Set up our app, set environment, and handle our requests—both boilerplate
  • Add our handler which utilizes our routes middleware imported above
  • Everything starting at app.prepare() will be also pretty boilerplate
    • Set up the server with const server = express();
    • Make sure we utilize our handler with server.use( handler );
    • Add the default route—important for the server to work.
    • Get our current port—not required, but I like setting a default so we don’t have to set a port in our package.json file
    • Add our listener to output errors so we still get errors in our logs
    • Finally, a little message when we start the server to let you know where we should be opening the browser to, in this case http://localhost:8080/

This is generally a pretty light server setup. Google around and check out the express docs, and you’ll probably find something very similar. Play around with it, and you’ll start to get an idea of what’s necessary and what can be updated.

Now, this isn’t going to work yet. We need to make a few updates to our project as it stands already.

In our package.json we’re going to update our dev and start scripts.

"scripts": {
  "dev": "node server.js",
  "build": "next build",
    "start": "NODE_PATH=. NODE_ENV=production node server.js"
},

We’ll just want to run our server directly instead of relying on the server that comes with Next.js. And for our start command, make sure we’re running in “production” mode.

Now running npm run dev will get our app going the same way it did before, but you may find that clicking any of the posts will still 404. This is because we need to add our new single post file.

Single Post Template

Let’s add, inside the pages directory, a new file named single.js. This will just need to match whatever you named your route in the routes.js file:

.add( 'single', '/posts/:slug' )

I’m just going to copy our index.js file just to make sure everything is working as expected:

import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
    <Navigation/>
    <h1>Your soon to be single post!</h1>
  </Fragment>
)

And they are!

NOTE: If this doesn’t work right away, you can stop and restart your server and that may resolve any issues.

Obviously, we’re not done here. We need to get our current route slug and display the data from a new API request. I’m going to make an additional API request here, just like we did with the /posts page, but get only the post data we need. Typically on a full-blown, React-based website, I’d probably do more to store and check for already-existing data, but in the interest of simplicity, here we go!

From our existing API we know we can get a post, “Hello World” for example, using the slug from our URL: https://wordpress.test/wp-json/wp/v2/posts?slug=hello-world.

So, what we’ll do is make this request and simply save that to props using the same getInitialProps function. Inside that function, we have access to context which we will use to get the current queried slug to make our API request.

So in single.js I’ll do this:

import Navigation from '../components/Navigation'
import React, { Component } from 'react'
import axios from 'axios';
import { Fragment } from 'react'

export default class extends Component {

  // Resolve promise and set initial props.
  static async getInitialProps( context ) {

    const slug = context.query.slug

    // Make request for posts.
    const response = await axios.get( `https://wordpress.test/wp-json/wp/v2/posts?slug=${ slug }` )

    // Return our only item in array from response to posts object in props.
    return {
      post: response.data[0]
    }
  }

  render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>Your soon to be single post!</h1>
      </Fragment>
    )
  }
}

I’ll convert my standard exported function into a class that extends the React Component, set up getInitialProps using context to get our slug, make an API request for our single post, and save that to our post prop. If all went well, nothing on the page should have changed, but we’ll have now successfully made a request for that data.

So, let’s get it rendered. In our renderer() function let’s make some updates, similar but not exactly the same, as our posts.js class using this.props.post for our data.

render() {
  return (
    <Fragment>
      <Navigation/>
      <h1>{ this.props.post.title.rendered }</h1>
      <article
        className="entry-content"
        dangerouslySetInnerHTML={ {
          __html: this.props.post.content.rendered
        } } />
    </Fragment>
  )
}

I’ve outputted my title into the H1, and using the dangerouslySetInnerHTML function, output the rendered content from our data. You’ll find if you just output { this.props.post.content.rendered } directly the content will not be rendered as HTML, so you would see this:

 

As long as we know where our content is coming from, we should be good to go here. So with those updates, we can refresh the page and should get this:

Perfect! What’s next?

Metadata

The one thing missing that will make this experiment a full-fledged website is metadata in our <head>. Things like page title or description, and things like the charSet or device-specific elements (width, name, content, etc), and whether or not we want search engines to see your site are required. Luckily, Next.js has an option for this. The usage is pretty easy.

I’ll do the work in our index.js file, but the same work can be replicated in posts.js and single.js respectively. First, I’ll import Head from Next.js. This gives us access to a new component in which we can add our meta information.

import Head from 'next/head'
import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
    <Navigation/>
    <Head>
      <title>This is our page title!</title>
      <meta name="description" content="This is an example of a meta description. This will show up in search results." />
      <meta charSet="utf-8" />
      <meta name="viewport" content="initial-scale=1.0, width=device-width" />
    </Head>
    <h1>Your new server-side rendered React.js app!</h1>
  </Fragment>
)

Nothing may look like it would have changed, but you’ll notice a couple of subtle changes.

We now have a page title in our tab:

And our meta description and information show up in the code:

Using next/head this will now render both client- and server-side, so our status as a fully-functioning SSR is intact. We could go one step further and add support for Twitter or Facebook/Open Graph meta also, but that will be on your plate for now.

Where Do We Go from Here?

If all you need is a homepage and some posts, you’re done. Granted, we could refactor and clean things up. Perhaps introduce caching or a data store to make things a little faster, but all in all, this is pretty lightweight as it stands with a pretty nice lighthouse score.

And tackling those deficiencies in performance, accessibility, and best practices wouldn’t require that much more work—just a matter of configurations and a few other files to include.

Past all that, however, you may want something a little more robust to fully replace your existing website. Well, just like any other part of this site so far, you’d need to build it. All of that WordPress functionality, like tag or category archive, search, etc., that’s on you. That would all take time and effort. If you have a plan and the know-how, go for it. I always feel good having built something that didn’t otherwise exist.

There are also plenty of existing frameworks out there with React.js or Vue.js that can accomplish more with varying levels of quality and varying depths of included functionality. So take a look around, and I’m sure you’ll find something that works for you and save some time. If you do find something, remember, it’s always a great idea to give back to the Open Source community and share any new ideas you might have.

WordPress + React Starter Kit

While we’re on the subject, might I recommend the WordPress + React starter kit from Postlight? This framework works in much of the same way that the app we just built does, although it supports more pages and functionality. At the base level, though, it’s a simple Headless React-based website with server-side rendering which supports proper SEO.

Return to Basics

Building an app this way really requires that we return to the basics. My feeling is that a lot of websites include features that are really great in a UX/UI perspective, but also unnecessary for the user to actually navigate or absorb the site—clutter, for lack of a certain term. Not to say that widgets or some of this extra functionality aren’t nice or sometimes useful, but my opinion is that a website should be discussed and planned and executed with finality. Knowing the who, what, why, and how of a website comes in handy when building a React-powered frontend website. Certain decisions need to be made as they’ll most likely be hard coded or the flexibility of the CMS (WordPress in this case) will be ignored.

Want to check it out for yourself? I’ve thrown everything up in a repo you can play around with that you can find here.

What do you think? Is the future of the internet JavaScript? Do you prefer a different framework for building your Headless website? Preact? Vue.js? Do you prefer a different setup altogether? Let us know in in the comments below.

Happy coding!

The post Headless WordPress with React and NextJS (Part 2) appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/01/10/headless-wordpress-with-react-and-nextjs-2/feed/ 12 19398
Headless WordPress with React and NextJS (Part 1) https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/ https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/#comments Thu, 03 Jan 2019 17:30:57 +0000 https://webdevstudios.com/?p=19391 Editor’s Note: The following is Part 1 in a two-part series titled, “Headless WordPress with React and NextJS.” You can read Part 2 here. Keep in mind that this article was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current Read More Headless WordPress with React and NextJS (Part 1)

The post Headless WordPress with React and NextJS (Part 1) appeared first on WebDevStudios.

]]>
Editor’s Note: The following is Part 1 in a two-part series titled, “Headless WordPress with React and NextJS.” You can read Part 2 here. Keep in mind that this article was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current content on Headless CMS and Headless WordPress, click here. Visit the WebDevStudios GitHub to access our Next.js WordPress Starter.

A little disclaimer: I refer to some of the things below as “easy.” To clarify, none of this is “easy,” but relative to the alternatives they could be considered “easier.”

The future of web development is JavaScript. It’s only natural when you consider the advancements in technology, device speed, and general user desire for more of an all-around, app-like experience. Libraries like Vue.js and React, among others, are leading the charge. You might be thinking that this sounds great. Why aren’t we all doing this? Let’s make the internet better, faster… we have the technology.

A GIF image from the TV show "Six Billion Dollar Man," used for a blog post about Headless WordPress with React and NextJS.

Limitations

There are, as is the case with any new technology, limitations. Using JavaScript to build an app for something like a Google Chrome extension or an iPhone/Android or Desktop app is fairly simple all things, considered.

  1. You have an idea.
  2. You build the thing.
  3. You use something like Electron or React Native to get your project in the hands of users.

I say “fairly simple” because you don’t have to necessarily worry about things that are required for a website to exist and for Google or Bing to find it, index it, and validate it.

Currently, Google requires a website to render on the server side in order to crawl the site for content, images, etc., which a pure JavaScript application does not do out of the box—although admittedly, Google is making strides to accommodate JavaScript apps. Also required are metadata, descriptions, title, etc., which isn’t available in the framework by default. I’m of the opinion that reactive JavaScript technology never intended to be used to build a website and only ever expected to be used as an application.

The Benefits of Headless

Other limitations are time and money. We don’t always have the ability to completely rebuild a website infrastructure and database(s) from the ground up. In an ideal world, a clean slate would be the way to go, but for the website that’s been around for 10 years and only needs a face lift, you’re going to spend more time trying to clean up the database than it’s probably worth, truth be told.

Enter the “headlessness” of it all. A headless website means just that—unlike a WordPress website handling the content and site rendering, the database and backend are decoupled from the frontend. More simply, your data lives in one place; your website lives in another. This can be a fantastic way to use your existing website data with a brand new shiny JavaScript website on the frontend. Most web platforms have an API that can be used to access your website’s data, from there, it’s a matter of manipulating that data to your whim. WordPress, for example, has its own Rest API baked into the core which makes it easy to display posts and pages without much fuss.

Of course, downsides exist with a headless setup. Let’s talk WordPress: widgets, themes or settings inside the admin for modifying your website are now void. If you want that feature, you have to build your own thing. If you want access to a plugin or menu data and those don’t have an API endpoint already, you need to make one. Those devs on GitHub that came before offer solutions, or plugins, or code snippets to help you along, but you can say goodbye to a simple ready-to-launch website out of the box. This will now take work.

Is It Worth the time?

I would argue yes. It’s ultimately up to you. If you’re not getting a lot of website traffic, or the entirety of your website consists of four pages and five blog posts, then the answer is no. If you’re consistently looking to improve your ever-increasing site traffic, user experience, speed, and interactivity, then yes.

In either case, if you’re thinking about going headless and decoupling your website in favor of a more future-proof, app-like website, then you should work smart, plan everything, and know what you’re getting into. So, let’s get started.

The Setup

We’ll be building a super-simple decoupled headless website using WordPress and React. In building a website, we have a couple of requirements we need to meet before pressing forward.

  • Must be server-side rendered so that our website is relevant to Google
  • Needs to be able to route pages the same way we would on any other website
  • Needs to be efficient and pass Google Lighthouse testing

Anything else I realize up front, like SEO considerations, we will need to build. I’ll touch on that a little bit, but we’ll save that for another blog post.

Given these requirements of the project, I’ve decided to use WordPress as my decoupled backend CMS and React alongside Next.js to handle the frontend app, SSR, performance, and routing. It’ll be a bit of work, but the payoff will be more than worth it.

Let’s Get Started

First things first, you’ll need to set up a WordPress install either online or locally. You can do that fairly quickly using Local by Flywheel. I won’t get into details here, but there are many options for doing this and many hosting providers that allow you spin up a new WordPress website in a matter of minutes, like WP Engine, for example.

For our new app, we’ll make a new folder so that we can get everything running in a different location from our WordPress install. There are repos and frameworks out there that have been pre-built or pre-configured to handle all of this setup for you, but we’re going to walk through the app step-by-step so that we can fully understand what’s going on.

Let’s get started! Create a new folder and install everything we need and then jump into that folder:

$ mkdir nextjs
$ cd nextjs
$ npm init
$ npm install --save next react react-dom axios

After running those commands you should see a package.json, package-lock.json file, and a node_modules folder.

We’ll replace the test script with some simple scripts inside our package.json file to allow us to easily start our project and build our necessary files.

"scripts": {
    "dev": "next -p 8080",
  "build": "next build",
  "start": "next start -p 8080"
},

NOTE: The -p 8080 specifies that we’ll be using port 8080 instead of 3000 to make sure our app is secure.

At this point, we basically have everything we need to get started. In the next few steps, we’re going to set up our folder structure, set up routing, configure our API request to get posts, and finally toward the end, talk about dealing with metadata.

Folder Structure

Anything inside a pages directory will be treated as a page. Anything inside components will be treated as a component (a non-rendered element). So, let’s add both.

Similarly, although we won’t set this up today, the styles folder could be used to add and compile any new CSS, SCSS, Sass, or LESS files on the fly.

Inside pages let’s add an empty file named index.js which we’ll use as our entry point. At this point, let’s test things out and make sure they are working as expected. Inside that file, let’s add one line of code (longhand):

export default () => {
  return <h1>Your new server-side rendered React.js app!</h1>
}

From there, let’s run the command npm run dev that we added above and visit http://localhost:8080/. If all went well, we should see:

Excellent! Now, let’s move on.

Routing

We’re going to make this pretty simple and just shove everything into a single component for now. Inside our components folder, let’s add a new file and name it Navigation.js. Inside this file we’ll setup our routes. For now, we’ll just provide access to our homepage, our index.js file, and our page of posts that we’ve yet to create. Let’s do that now. Inside pages let’s add a new file called posts.js and add a similar bit of code to separate it from our index.js file.

export default () => {
    return
Our Posts Page!

}

We’ll change this up later, but for now, we’ll use this to make sure our routes are working once they’re set up.

Here’s the final result for our simple Navigation.js router.

import Link from 'next/link'

export default () => (
    <ul>
        <li><Link href="/"><a href="/">Home</a></Link></li>
        <li><Link href="/posts"><a href="/posts">Posts</a></Link></li>
    </ul>
)

We’ll import Link from next/link which is already baked into Next.js. It operates in much the same way that Link from react-router-dom would. We’ll wrap the <a href> in the Link component as directly adding a string to a Link was deprecated, so we avoid some errors here, although, omitting it would still technically work. This is pretty simple now, but we’ll get a little more complicated later on.

Now that that’s done, let’s go back to our index.js and posts.js files inside the pages directory and make some updates.

import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
      <Navigation/>
      <h1>Your new server-side rendered React.js app!</h1>
  </Fragment>
)

and

import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
    <Navigation/>
    <h1>Our Posts Page!</h1>
  </Fragment>
)

I like to use Fragment whenever I can to avoid unnecessary extra markup. The function only needs a wrapping parent element, but a div would work just fine.

We end up with something like this:

Not pretty, feel free to add some style objects to make that a bit nicer, but for now, it works, so we’ll go with it. If you’re still running your project via npm run dev you’ll find that if you click “Posts” you’ll see your posts page you created earlier:

Our URL is updated and our content is dynamically updated. This is a fairly simple use of routing and all we need to get things working. I’d suggest, however, to avoid having to call your Navigation component on every new page you make, look into the React Router Docs to see how you might be able to extend its functionality.

Let’s Get Our Data

So we’ve set up our simple app, we’re rending both server- and client-side and we’re routing, very simply. Before we can get into building our app further, we need to get our data from our WordPress install we set up at the top.

Now, I’m going to use a package called Axios to make API requests. React docs recommend using fetch, but I’m not a huge fan specifically since there are some compatibility issues and some extra steps involved in those requests. Axios has graceful fallbacks for older browsers and takes the guesswork out of making an API request. It makes things more, for lack of a better term, simple.

We’ll be making our API request inside the posts.js file we created.

First, I’ll import axios and react:

import axios from 'axios'
import React, { Component } from 'react'

If I were building a more complex website, I’d probably think about writing reusable functions for things like this, but for sake of clarity, I’m going to have each route make a request.

Next, I’m going to convert my default function into a class that extents React.component so that we can set our initial props (our API data) and render our component—the stuff we’ve already built.

import Navigation from '../components/Navigation'
import React, { Component, Fragment } from 'react'
import axios from 'axios'

export default class extends Component {

  // Resolve promise and set initial props.
  static async getInitialProps () {

    // Make request for posts.
    const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts')

    // Return response to posts object in props.
    return {
      posts: response.data
    }
  }

  render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>Our Posts Page!</h1>
      </Fragment>
    )
  }
}

I’ve moved my original default function into the render function.

Let’s break down the API request.

// Resolve promise and set initial props.
static async getInitialProps () {

  // Make request for posts.
  const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts')

  // Return response to posts object in props.
  return {
    posts: response.data
  }
}

I need to make sure to make an async request, and resolve the promise we’ll get via axios and then assign that data value to a prop that we can access inside our render function.

We will then access that data inside our render function as this.props.posts. And we’ll use some JSX to output each post title into a list.

render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>Our Posts Page!</h1>
        <ul>
          {
            this.props.posts.map( post => {
              return (
                <li key={ post.id }>{ post.title.rendered }</li>
              )
            })
          }
        </ul>
      </Fragment>
    )
 }

For now, we’ll just output a simple list of rendered titles and end up with something like this:

Fantastic! So let’s take a look at our final posts.js file:

import Navigation from '../components/Navigation'
import React, { Component, Fragment } from 'react'
import axios from 'axios'

export default class extends Component {

  // Resolve promise and set initial props.
  static async getInitialProps() {

    // Make request for posts.
    const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts' )

    // Return response to posts object in props.
    return {
      posts: response.data
    }
  }

  render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>hOur Posts Page!</h1>
        <ul>
          {
            this.props.posts.map( post => {
              return (
                <li key={ post.id }>{ post.title.rendered }</li>
              )
            })
          }
        </ul>
      </Fragment>
    )
  }
}

What’s Next?

From here, we’ve done what we aimed to. Headless application? Check. Server-side rendered? Check. Routing? Check. That said, what we’ve built really doesn’t provide a final product, something like what you would expect to see. You might, for example, expect to be able to click one of those posts and read the content or expect the title in the tab to change based on your route, or for the head description to change, or for any content that exists behind the scenes update as we navigate through our app.

We’ll take a look at that in Part 2.

The post Headless WordPress with React and NextJS (Part 1) appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/feed/ 12 19391