Vinnie James
Vinnie James

Reputation: 6052

Rendering React Components Client-side via WordPress WP-API

I'm interested in experimenting with React and WordPress WP-API, I quickly put together a proof of concept page template below.

Curious, what are the performance implications of rendering API data on the client with React versus allowing WP to render as usual on the server in PHP?

<div id="react"></div>

<script type="text/babel">

var WpPage = React.createClass({
  getInitialState: function() {
    return {
      id: '',
      date: ''
    };
  },

  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var pageObj = result;
      this.setState({
        id: pageObj.id,
        date: pageObj.date
      });
    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    return (
      <div>
        <p>{this.state.id} :: ID</p>
        <p>{this.state.date} :: DATE</p>
      </div>
    );
  }
});

ReactDOM.render(
  <WpPage source="/wp-json/wp/v2/pages/{id}" />,
  document.getElementById('react')
);
</script>

Upvotes: 2

Views: 285

Answers (1)

Ank
Ank

Reputation: 178

I think with React you can have better performance and experience for users by following some methods-

  • You can define a base layout with static menus and footer and load the content through AJAX with react-router CSSTransitionGroup here is a good example (codepen.io/luisrudge/pen/QbEeOR/), this way users can have seamless web experience.
  • You can have websockets for communicating with wordpress more faster.
  • As you will always call API for results on every content component you may want to consider storing some content in localStorage or session for efficiency and less API calls. (or maybe use Flux?)

Upvotes: 1

Related Questions