Isomorphic JavaScript, JavaScript, Node.js

Isomorphic WordPress Applications using NodeifyWP at WordCamp Lancaster 2017

This weekend I'll be presenting on "Isomorphic WordPress Applications using NodeifyWP". I'll also be discussing the NodeifyWP Environment – a Dockerized environment pre-setup for running NodeifyWP applications.

Standard
JavaScript, Node.js

Modifying the DOM using jQuery within React Components in Isomorphic Applications

React works awesome within isomorphic JavaScript applications. There are a number of frameworks and design patterns available for accomplishing this. My personal favorite is Fluxible.

In an isomorphic application, your JavaScript renders views both server side and client side. Essentially the same view code is being executed client side and server side. At first it was hard for me to wrap my head around that concept. React components can be used to implement those views.

jQuery, especially it’s UI libraries, is a useful client side tool. Since jQuery itself relies on a client side DOM, we can’t use it server side. Therefore we need to execute jQuery code in our React components but only during client side renderings.

Here is an example ES6 React component using JSX. Let’s pretend we are using this as a view in an isomorphic JavaScript application where it is being rendered both server side and client side:

import React from 'react';
class MyComponent extends React.Component {
  render() {
    <div>
      This is my React component. <a title="Checkout my tooltip text.">Tooltips</a> are pretty helpful.
    </div>
  }
}

Let’s use the jQuery tooltip plugin to power our tooltip. First make sure you include jQuery and the tooltip plugin in your page output. It usually makes sense to add external scripts to your base React component.

Let’s setup our tooltip code:

import React from 'react';
class MyComponent extends React.Component {
  componentDidMount() {
    jQuery(React.findDOMNode(this.refs.tooltip)).tooltip();
  }

  render() {
    <div>
      This is my React component. <a ref="tooltip" title="Checkout my tooltip text.">Tooltips</a> are pretty helpful.
    </div>
  }
}

First, we added a ref tag to our tooltip. This let’s us reference our component node later. We then added a componentDidMount method. componentDidMount executes after initial rendering on client side only. Refer to the React lifecycle for more details on this. React.findDOMNode selects our tooltip node based on ref. We then wrap the node in jQuery and call the jQuery tooltip method. Since componentDidMount executes client side only this works perfectly and doesn’t cause any issues with our server side rendering.

Standard