Today I want to tell you a story about our own personal journey through React, Redux, Next.JS and the WordPress REST API which now is a standard feature starting on version 4.7.0.

So it all begun as a mere idea: what if we could port the default Wordpress theme into a Universal React App? That way we could decouple the FrontEnd from the CMS, build something awesome and also learn a bit about React and all the hype surrounding it? That’s when R+D team decided we would put in the time to make this happen.

Enter NextJS

One of the benefits of using React for developing stuff is that it can be used both on the client side and on the server side. A benefit to doing this approach is that someone making connection the first time will get a fast response since that initial chunk of data is parsed by the server and served as just HTML and CSS so the feel of the website is that everything is fast and snappy, while at the same time the JS is loaded later to be used once its loaded. This means that we get the benefit of a server rendered website which is fast to load and even if we have javascript disabled on the client we can still see things and get indexed by Google and keep our SEO intact, we also get the benefits of a SPA which is that subsequent views will load really fast since we are only fetching son data from the server. The issue with this approach is the whole configuration process that needs to happen to even be close to achieving something like this. Luckily for us we found an awesome Open-Source project made by Zeit called Next which does exactly this in a just-add-water way so thats awesome for us, the whole procedure is as easy as the video they use on their website:



Another thing I learned while this and looking at their example is that they like to use StandardJS as a linter with the babel-eslint parser (mainly to work fine with React) this is done as follows:

yarn add standard babel-eslint

And then adding those on our package.json like so:


{
...
"dependencies": {
		"babel-eslint": "^7.1.1",
		"next": "^1.2.3",
		"standard": "^8.6.0"
	}
},
...
"standard": {
	"parser": "babel-eslint"
}


I am a heavy vim user myself (NeoVim) actually so there’s an awesome way of auto-linting the files on save by installing a couple things:

  • First install StandardJS globally and Babel-eslint: npm install -g standard babel-eslint
  • Then install Syntastic Plugin for Vim (I use Plug but you can use Vundle, Pathogen, etc…) Plug 'vim-syntastic/syntastic', { 'do': 'npm install -g standard babel-eslint' }
  • Now lets just add the magic to our .vimrc


" StandardJS
let g:syntastic_javascript_checkers = ['standard']
" StandardJS autoformat on save: needs standard-format global npm package
autocmd bufwritepost *.js silent !standard --fix %
set autoread


That’s it! Now every time we save our JS it will be properly formatted (great for teamwork since now everyone will have the same coding style!)

If Vim isn’t your cup of tea remember there are plugins for Atom, Sublime, Brackets, Visual Studio and many more. Check here for more details

How do I even React?

So after your initial JSX syntax shock its time to actually do something with it:


import { Component } from 'react'
class HelloWorld extends Component {
	render() {
		return (
			<h1>Hello World</h1>
		)
	}
}
export default HelloWorld


That’s actually really simple but the real power comes from using props and then using Components as Lego blocks to build stuff, its really awesome to use as a developer, like super readable take for example the Sidebar component:


import { Component } from 'react'
import SearchWidget from './SearchWidget'
import PostsWidget from './PostsWidget'
import CommentsWidgetContainer from './CommentsWidgetContainer'
import CategoriesWidgetContainer from './CategoriesWidgetContainer'

class Sidebar extends Component {
  render () {
    return (
      <div>
        <SearchWidget />
        <PostsWidget />
        <CommentsWidgetContainer />
        <CategoriesWidgetContainer />
      </div>
    )
  }
}
export default Sidebar


You can’t even deny that wasn’t fun to read, the DX (developer experience) going on with React is strong, and really fun to use.

And so I thought until it came the time were we needed to manage our state…

Redux: Or why bismuth crystals are a big deal (?)

So remember how the way React makes you work is by making everything into a small independent component? That’s cool and stuff right until you need to share data between components and listen to events on other components or send data upwards (by default on React data flows from the root level component down to its children and not in reverse like on Angular 1 for example)

In a super tight nutshell what Redux does is that firstly it creates a single Object that represents the whole state of the app. Wait, what? Yeah, for example lets imagine in our Wordpress example we want to represent our posts in a javascript object:


let store = {
	posts: [{
		id: 1,
		name: 'post 1'
	}, {
		id: 2,
		name: 'post 2'
	}]
}


So now comes the serious business, Redux approach to state is that state is immutable, that means that we don’t actually change the state instead we provide a new state by defining an action which is equivalent of saying a command out loud with the minimal new representation of a new state.

How redux manages to pull that out is with something called a reducer which is basically a javascript switch in which you do stuff based on the action type you get:


function reducer (state = {}, action) {
	switch (action.type) {
		case 'ADD_NEW_POST':
			return Object.assign({}, state, {
				posts: state.posts.concat(action.post)
			})
		default: return state
	}
}


For example adding a new post:

store.dispatch({
	type: 'ADD_NEW_POST',
	post: {id: 3, name: 'post 3'}
})


Would result in getting a new state like:


store.getState()
// =>
{
posts: [{
		id: 1,
		name: 'post 1'
	}, {
		id: 2,
		name: 'post 2'
	}, {
		id: 3,
		name: 'post 3'
	}]
}


The thing with redux is that you need to make everything into a pure function and you can’t mutate the state so even though those concepts are pretty simple we still get articles where a bismuth crystal is the cover because obviously thats the only way we could describe redux right?

React-redux aka the savior

So once we get our Actions, Reducers and Store going on properly we need to glue those in our React app so basically react-redux comes to the rescue here with 2 things mainly:

  • Provider which is a wrapper for your entire app which basically places the store in a way that can be heard globally plus it adds a couple of event listeners so that any component no matter where it is can read and dispatch actions to the store.
  • connect which makes our components able to read and/or dispatch actions to the store.

The cool thing here is that react will re-render automagically if the data on the store changes keeping everything in sync.

So the way we use connect is described on its docs however I feel like its a bit tough on newcomers given that is really a simple thing here’s an annotated example:


import { Component} from 'react'
import { connect } from 'react-redux'

// what this does is that it will read from the store and map whatever we tell it to a prop we say

function mapStoreToProps (store) {
	return {
		posts: store.posts
	}
}
// so now in our component this.props.posts === store.posts
// and they will be on sync ;)

class Posts extends Component {
	render() {
	let { posts } = this.props
	return (
		<div>
			{posts.map(post => (
				<h1>{post.name}<h1>
			))}
		</div>
	)
	}
}
export default connect(mapStoreToProps)(Posts)


Ok so now we’re able to have the components talk to each other while at the same time being independent one from another, great! (Hence the bismuth stones lol, everything’s a container)

We are we now…

So right now we have delivered a pretty barebones MVP version of a Wordpress Theme just a blogging one with search and native commenting functionality, just enough to prove the concept, show it to the community and of course open source it to improve it even further. I think the standard twenty seventeen Wordpress theme has some fundamental html + css design that of course is not meant to be used in a components world since a WHOLE lot of layout and views depend on classes added (or not) to the body element this is of course because of the way Wordpress and PHP do their thing.

What’s Next…

For this project we are really happy to announce we will be open-sourcing all of the code we used so maybe you can use it as a starting point for your own Wordpress powered blog which you could then deploy using now as for us we also hope this will open the doors for new react projects since we actually loved using it a lot.

NextJS might not be perfect but it sure is a damn good starting point and some expected new changes will surely take it to the next level. (Actually at the time of right before publishing this, next already allows for extra customization so that’s extra awesome ❤️)

We can’t wait to hear your feedback and contributions to this awesome project.

Here is the link to the code and don’t forget to check the demo: