So far in our series, we’ve loaded some data into WordPress to play with and made sure we can access it via the REST API. Along the way, we’ve introduced a number of core concepts and simple tools you can use to start experimenting yourself, even if you’re not a tech whizz.
This time around, it’s time to consider how we might go about handling things on the front end. We need a nice framework we can use to pull data out of WordPress via the REST API and display it. It’s almost certainly going to involve a JavaScript-powered solution. But which one?
That’s exactly the question we’ll be pondering below. We’ll briefly survey the landscape of possible options, select one and introduce it, and then look at simple steps to get up and running. Let’s start, though, with a quick reminder of why JavaScript makes sense in this context.
JavaScript Is Eating the World
JavaScript, as Kevin Lacker recently put it, is eating the world. It’s come a long way from its origins as a hastily put together short-term solution at Netscape and is now, by some measures, the most popular programming language in the global development community. In terms of front end web development in particular, it’s fair to say that JavaScript is effectively the lingua franca of the web these days.
It’s also, as Matt Mullenweg was keen to stress in his 2015 State of the Word address, very much the future of WordPress. The recent arrival of Calypso pointed the way quite dramatically towards where much of the platform is heading – a stable and secure background WordPress core, housing data that’s consumed by an ever-increasing set of wider external services, many of them powered by JavaScript.
JavaScript is also blessed with a number of stable and mature front end frameworks that developers can use to work quickly and effectively. Let’s move on to look at some of the main ones.
The Leading JavaScript Framework Contenders
As with any other programming language, there’s a huge amount to be said for sticking to DRY and KISS principles and using some sort of framework to take care of a lot of the heavy lifting when you’re dealing with JavaScript.
A quite baffling number of JavaScript frameworks have winked in and out of existence over the last few years, but in terms of stability and active development, the practical choice here basically boils down to one of four:
- Backbone.js. Created by Jeremy Ashkenas, Backbone was one of the first frameworks out of the starting gate back in 2010. Its combination of compactness and flexibility led to early adoption by an impressive list of high-profile sites, and projects including WordPress.com and WordPress core.
- Ember.js. Where Backbone presents a deliberately stripped-down set of possibilities to build off, Ember is a substantially more ambitious and opinionated affair. The framework was created in 2011 by Yehuda Katz of jQuery and Ruby on Rails fame, and is designed to help developers tackle large-scale projects quickly and effectively. It can be seen in action on a host of marquee sites including Discourse, Groupon, and LivingSocial.
- Angular.js. Billing itself as a “Superheroic JavaScript MVW Framework”, AngularJS is Google’s dog in the framework fight. It offers a relatively easy learning curve and a thriving worldwide community of users. The framework’s move from Version One to Version Two was a little controversial, however, and it does require a bit of performance-related hand-holding when deployed at scale.
- React. Arriving in 2013, Facebook’s React is a more recent addition to the field, but has quickly attracted an army of enthusiastic early adopters including (somewhat obviously) Facebook itself, Instagram, Flipboard, Netflix, and a host of others. React has won plaudits for its speed, comparative simplicity, and easy mobile integration in the form of React Native.
The solution we’ll be using to power our own humble app is, in fact, React. It’s arguably the most modern of the bunch, and promises an onboarding process that won’t completely melt the minds of non-developers. With the ongoing dominance of services such as Facebook and Instagram who rely on it, it also won’t be going out of fashion any time soon.
Let’s move on to explore React in a little more depth.
Introducing React from Facebook
The first thing to clarify is that React is, strictly speaking, a library rather than a framework. As the project homepage states loud and clear, it’s a “JavaScript library for building user interfaces”. It also takes a different approach to the other three solutions we mentioned above.
Rather than trying to solve for every part of putting together a complete online application (as in, for example, Ember), React uses a component-based approach to focus heavily on the UI part of the problem.
It enables you to define highly modular UI components that live in their own discrete world and can be easily reused and reasoned about. To put it in slightly more formal terms, you can think of React as the V in MVC.
If you’re looking for a solid general introduction to React, the project documentation is nicely put together, with Pete Hunt’s Thinking in React piece a particularly useful jumping-off point. The React Fundamentals course from egghead.io is also an excellent resource, as is the Rapid React course from LearnCode.
React can be used in conjunction with other solutions (such as Flux and Redux) to create complex, full-blown applications at truly enormous scale. It can also be used to quickly build out native apps for both iOS and Android in the form of React Native. We’re not trying to build a Doomsday Machine here, however, so we’ll be keeping things as vanilla as possible.
Let’s start with seeing if we can get React running locally.
Is This Thing On? (Redux)
Have a quick look around many of the React tutorials online and you’ll soon find yourself confronted with a wall of opinion around background tooling, involving things like browserify, Bower, and webpack. These options are well explained in the React package management pages, but we’ll be looking to sidestep that rat’s nest entirely by simply downloading the React Starter Kit locally.
The Starter Kit gives you a set of local files you can call directly via the browser. Using DesktopServer, I’ve created a new local site called www.thoreauapp.dev and simply copied the contents of Starter Kit into it.
Firing up our ‘site’ locally, we see just the default index.html page created by DesktopServer. I’m now going to replace the contents of that file with the Hello World script from the Starter Kit documentation.
A quick refresh of the page, and we see the following inspiring results:
It’s not the most visually compelling page in the world, but it proves one crucial thing: we have React running locally, and it’s capable of displaying content. Now let’s see if we can get it talking to WordPress.
Performing a Basic React/REST API Test
If you’ve read the previous piece, you’ll remember that we have a local REST API-enabled WordPress install running at http://walden.dev/. If we call http://walden.dev/wp-json/wp/v2/posts via HTTP, we’ll get a full list of all posts in the install. I’m going to use that to do a very quick check that I can get React talking to WordPress via the REST API.
The code below is based on the React documentation tips for loading external data. Don’t worry about the ins and outs of it too much for now; I just want to see if we can get our separate components talking to each other by replacing my index.html file with the following code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello React!</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <script src="build/react.js"></script> <script src="build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> var ThoreauQuote = React.createClass({ getInitialState: function() { return { quoteContent: '', quoteID: '' }; }, componentDidMount: function() { this.serverRequest = $.get(this.props.source, function (result) { var firstQuote = result[0]; this.setState({ quoteID: firstQuote.id, quoteTitle: firstQuote.title.rendered, quoteContent: firstQuote.content.rendered }); }.bind(this)); }, componentWillUnmount: function() { this.serverRequest.abort(); }, render: function() { return ( <div> <b>Quote ID:</b> {this.state.quoteID}<br/> <b>Quote Title:</b> {this.state.quoteTitle}<br/> <b>Quote Content:</b> {this.state.quoteContent}<br/> </div> ); } }); ReactDOM.render( <ThoreauQuote source="http://walden.dev/wp-json/wp/v2/posts" />, document.getElementById('example') ); </script> </body> </html>
Another quick refresh of the browser, et voila!
It’s an admittedly deeply unimpressive visual result, but we’ve done something pretty major here – we’ve used React to call data from the REST API, parse it, and then display results on the screen. At this point, we can confidently say that we’re in business!
Conclusion
JavaScript-powered front end solutions are set to be a huge part of the WordPress world very soon, so now is an excellent time to start exploring their potential. Having briefly outlined the other major contenders for building our simple app, we decided to plump for React – a solution that’s set to be around for many years to come.
We’ve also made quite a bit of progress towards our eventual goal. Previously, we knew that WordPress was merrily serving up content via the REST API. We also now know that we can get React running locally, and consuming and displaying that content.
Stay tuned for the next part of our series, where we’ll start digging into the details of working with content in React in more detail. We’d love to hear from you if you’re following along at home. Get in touch via the comments section below and share your thoughts!
1 Comment