How to Build Plugins for React Apps in WordPress – Best of 2021

Build Plugins for React Apps in WordPress
Build Plugins for React Apps in WordPress

Do you want to build Plugins for React Apps in WordPress? In case you’re not creating an app that needs plugin support, you can then also apply these concepts to create more powerful large React apps. In this article we will show you how to build plugin for React Apps in WordPress.

What is React.js?

React JS is a JavaScript framework that has been under development by Facebook since 2012. The main cause that you are hearing more about it recently is because of the fact that Facebook did not publicly announce the project until 2015.

However thousands of PHP developers had to become articulate with JavaScript to be able to take benefit of the newly tech-stack and create apps on top of WordPress the React way.

Read Also: Adding Javascript and Styles in WordPress

Advantages of Using React App

  • React isn’t a framework as it is a library which gives a informative method of defining UI components.
  • Access to the native world. React App Native allows you to create mobile apps using only JavaScript.
  • Complete separation of data and presentation. React App provides slightly more than a presentation layer.
  • Writing React template is very similar to writing HTML with interpolation thanks to JSX.

Disadvantages of Using React App

  • Build tools are important for all front-end apps but the simplest, decent build tools are highly suggested.
  • Restrictive Licensing

Why Plugins are Required?

There are many plugins for customizing the authoring interface, add brand new sidebar, register their own settings panels, and much more. It’s very powerful as the WordPress dashboard supports plugins. You can also create a mobile app with wordpress.

Where plugin is defined as a type of software that contains a group of functions that can be added to a WordPress website. They are used to provide additional functionality to your application.

As Sidebar is a theme feature, which is basically a vertical column provided by a theme for displaying information other than the main content of the web page. The usage of sidebars changes and it depends on the choices of the theme designer.

Also, theme is a group of stylesheets and templates that are used to describe the appearance and display of a WordPress site. And, templates are those files which control how your WordPress site will be displayed on the Web. WordPress is written in PHP and plugins are completely rendered on the server. 

That was brilliant back in 2004, but more than a decade later, things have changed. If rebuilt today, the WordPress dashboard would possibly be a client-side JavaScript application written in React, and it would support plugins as first-class objects.

Read More: List of Top 10 WordPress Plugins To detect Malicious Code in your site

Supporting Plugins With React App

React App grants you illustrating self-contained components so it’s best foundation for plugins. But once we started creating, we found three major key issues:

  • Plugin components require to access state and want to implement features that differ state in uncertain ways.
  • Plugin components need to display somewhere in the application, but another components don’t know how to render them. Adding them straightly to the DOM will produce invariant errors.
  • They may throw exceptions, and they could crash the whole app.

Extending the Flux Pattern 

We are extending the Flux Pattern for Shared State in Large Applications. Letting unknown 3rd party components to mutate shared state becomes largely problematic in large apps. And We’ve fix this by integrating our Flux stores and exposing flexible interfaces for components.

What is Flux?

For the complete understanding of Let’s see the example of building a simple chat app, having list of messages in its main view. This is the way how state flow works via the Flux pattern.

flux
Flux – Store – Element – Dispatcher – Build Plugins for React Apps in WordPress
  • The green Store is a object that holds the data or information. In the above example it is holding list of messages so we call it MessageStore.
  • The blue Component is liable for rendering data. In the above example, this renders the list of messages.
  • The global dispatcher controls routing actions and events generally from a component back to a store. By clicking on a “star” button on a message that will broadcast an action all over the system, which would update the store and cause components to re-render. Flux makes it very difficult for views to get out of sync with the underlying state.

From One Store to Many

If you need to extend this chat app for managing multiple ongoing threads with various people. This is very easy as we just create a ThreadStore and ThreadList. At the time a new thread is chosen, the MessageStore requires to change the list of active messages in order for the MessageList to re-render. We do this by having the MessageStore listen to events from the ThreadStore.

flux-simple
Thread Store – Message Store – Build Plugins for React Apps in WordPress

Linking stores also a usual design pattern in Flux, and provides way to interdependent data structures. Adding more connected stores can make this fastly grow out of control. It’s difficult to reason about where data is being changed completely, and easy to announce complicated circular dependencies. This doesn’t scale, specifically with plugins.

flux-complex
Translation Store – Build Plugins for React Apps in WordPress

For example if you need to create a translation plugin. This plugin generally needs to transform the data, so we have to write a TranslationStore as shown in purple. It will translate outgoing messages from the DraftStore and also publish translated messages to the MessageStore.

The OmniStore

Our quick solution is to centralize the app’s data in an OmniStore. It is a single top-level store that acts as a source of truth and removes the dependency chain. This store is just like a frequent Flux store, except that it now holds all the primary application state. Via this design, other stores only cache and aggregate subsets of the central data, and sell it to to individual components.

omni-store
Omni Store – Build Plugins for React Apps in WordPress

This pattern is simpler to reason about when creating and debugging. By decoupling earlier dependent stores, it grants us to safely introduce 3rd party plugin stores. Now the Translation Store can straightly update data in the Omni Store (yellow), which will broadcast notifications and occur the significant components to re-render.

Dynamically Injecting React Components

We introduced a 3rd party plugin for translating messages in the previous example. But this plugin possibly also requires a “translate” button at the bottom of the message composer next to the send button. Here’s what the JSX might look like:

static-components.jsx
<div id=“actions”>
<UndoButton draft={this.props.draft} />
<AttachFileButton draft={this.props.draft} />
<SendButton draft={this.props.draft} />
// new component here!
</div>

The current draft is passed as a prop to every of the three buttons. But for enabling our React app to dynamically inject a new TranslateButton:-

  • First of all move the list of buttons we are rendering from JSX to an array. This is a small React trick, and will render the accurate same content. Our app can easily pass the same props to all of them as each button’s styling and behavior is self-contained. Where, array uses just one variable and lets you save multiple pieces of data using the same variable.
component-variables.jsx

render: function() {

var componentClasses = [

UndoButton,

RedoButton,

AttachFileButton

];

return <div id=“actions”>{

componentClasses.map(function(componentClass){

return <componentClass draft={this.props.draft}/>;

});

}</div>;

}

  • At next upgrade the components array into a Flux store, This new Component Store has an componentClasses() method to return an array of component constructors. The new toolbar component requires to notice the Component Store and render the passed component items.
injected-components.jsx

<div id=“actions”>

<InjectedComponentSet

location={‘composer-actions’}

passedProps={ {draft: this.props.draft} } />

</div>

Our major goal is to write functions that perform on data and return data. JSX is a syntactic sugar for the usual data shape we use all the time in React. And if we treat views as just data, we can take benefit of the same Flux patterns used throughout the app.

Maintaining an index of components in a Flux Store has a few benefits. Components can leverage actual mixins and patterns, and listen to the store for changes in available components. This permits the app stays in sync as plugins are loaded and unloaded. We can also build Flux Actions for registering and unregistering components, which makes these processes globally viewable within the application.

The props passed to an injected component are necessarily the component’s API. They can be obviously documented for developers, and display the true application state (unrelated to the DOM state).

Isolating Unknown Components

One of the drawback for a globally reactive application is that exceptions in lifecycle or render methods can sink the whole app.

And we fix this by rendering components in a new React root. That means we render a placeholder div, and then manually call React.render within a try/catch block. For managing the lifecycle, we trigger this on all component update events (componentDidUpdate / componentDidMount), and also call

React.unmountComponentAtNode when components unmount.

React.render is created to be flexible, and supports rendering fresh or update existing views.

react-wrap
React Wrap – Build Plugins for React Apps in WordPress

This lets us handle any errors in the render methods, and securely isolate, kill, and report poor quality components. We can display helpful error messages to users and developers when things go wrong.

CLOSING THOUGHTS

We hope that this article helped you in building Plugins for React Apps. As you can easily build it by reading the above article carefully.

You can contact to our WordPress Customer Service team just dial + 1 844 275 0975(Toll-Free) for the instant help and service relate to WordPress.



Leave a Reply