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
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.
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.
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:
1{2...3"dependencies": {4 "babel-eslint": "^7.1.1",5 "next": "^1.2.3",6 "standard": "^8.6.0"7 }8},9...10"standard": {11 "parser": "babel-eslint"12}
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…)
1Plug 'vim-syntastic/syntastic', { 'do': 'npm install -g standard babel-eslint' }
- Now lets just add the magic to our
.vimrc
1" StandardJS2let g:syntastic_javascript_checkers = ['standard']3" StandardJS autoformat on save: needs standard-format global npm package4autocmd bufwritepost *.js silent !standard --fix %5set 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:
1import { Component } from 'react'2class HelloWorld extends Component {3 render() {4 return (5 <h1>Hello World</h1>6 )7 }8}9export 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:
1import { Component } from 'react'2import SearchWidget from './SearchWidget'3import PostsWidget from './PostsWidget'4import CommentsWidgetContainer from './CommentsWidgetContainer'5import CategoriesWidgetContainer from './CategoriesWidgetContainer'67class Sidebar extends Component {8 render () {9 return (10 <div>11 <SearchWidget />12 <PostsWidget />13 <CommentsWidgetContainer />14 <CategoriesWidgetContainer />15 </div>16 )17 }18}19export 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:
1let store = {2 posts: [{3 id: 1,4 name: 'post 1'5 }, {6 id: 2,7 name: 'post 2'8 }]9}
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:
1function reducer (state = {}, action) {2 switch (action.type) {3 case 'ADD_NEW_POST':4 return Object.assign({}, state, {5 posts: state.posts.concat(action.post)6 })7 default: return state8 }9}
For example adding a new post:
1store.dispatch({2 type: 'ADD_NEW_POST',3 post: {id: 3, name: 'post 3'}4})
Would result in getting a new state like:
1store.getState()2// =>3{4posts: [{5 id: 1,6 name: 'post 1'7 }, {8 id: 2,9 name: 'post 2'10 }, {11 id: 3,12 name: 'post 3'13 }]14}
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:
1import { Component} from 'react'2import { connect } from 'react-redux'34// what this does is that it will read from the store and map whatever we tell it to a prop we say56function mapStoreToProps (store) {7 return {8 posts: store.posts9 }10}11// so now in our component this.props.posts === store.posts12// and they will be on sync ;)1314class Posts extends Component {15 render() {16 let { posts } = this.props17 return (18 <div>19 {posts.map(post => (20 <h1>{post.name}<h1>21 ))}22 </div>23 )24 }25}26export 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: