Integrating React with Other Libraries

Learn via video courses

Overview

ReactJS is a JavaScript library created by Facebook. You can export your components and import them wherever you like in your files. ReactJS is similar to first importing the component and then using it.  There are numerous JavaScript or ReactJS libraries available, such as toastify, UUID, etc. They are simple to incorporate into your ReactJS application.

Introduction

The open-source Javascript package ReactJS is used to create front-end apps. It is the industry's most desired web framework and the second most widely used web framework after JQuery.

Many libraries are available in plain Javascript or as JQuery plugins. Datatable.js is one of them. We don't have to recreate those libraries and waste time and energy.

Any web application can use React. It can be embedded in other apps and, with care, other web applications can be integrated with React.

We'll examine how to include JavaScript libraries or other libraries in a React application. ReactJS is a JavaScript library developed by Facebook. The ReactJS workflow allows you to export components and then import them wherever you'd want in your files, much like importing something initially, and then using the component later in the code. Many libraries for JavaScript or ReactJS are available, including toastify, UUID, and others. You may easily add them to your ReactJS application.

Creating A React App And Installing Modules

  • Step 1: Use the following command to create a React application.

  • Step 2: Use the following command to move to your project folder after creating it, i.e., foldername.

  • Step 3: Once the ReactJS application has been created, use the following command to install the UUID module.

The project structure will look like this:

Example:

Now, in the App.js file, add the following code. Our default component in this case is App, where our code is written. The user can see the ID we created using the v4() method from the UUID module, which varies with each refresh.

But then how do you run your React application?

From the project's root directory, issue the following command to run the application.

If you open your browser now and navigate to http://localhost:3000/, you will see the final output.

Using DOM Manipulation Plugins

React ignores changes to the DOM (Document Object Model) done outside of the framework. When another framework updates the same DOM elements, React appears confused and has no way of resolving the issue.

The Document Object Model (DOM) is an API for representing and interacting with HTML documents. The DOM for a web page is created by the browser when a page is loaded. The document is represented by the DOM as a node tree, with each node denoting a different section of the document. It could be a component, text, etc., depending on how that website was created.

This is not to argue that using React in combination with other DOM manipulation techniques is difficult or even impossible; you just need to know what each does.

The simplest method to prevent conflicts is to prevent the component from updating. This can be achieved by rendering components, like an empty div, that is not updated by React.

Way to Avoid Conflict

To illustrate this, let's create a wrapper for a basic jQuery plugin.

To the root DOM element, we will now add a reference. We'll grab a reference to the element within componentDidMount and pass it to the jQuery plugin.

To prevent React from modifying the DOM after mounting, we can return an empty <div /> from the render() method. Because the div element has no children or properties, React is not required to update it, allowing the React with JQuery plugin to control that region of the DOM:

Notably, we defined the lifecycle methods componentDidMount and componentWillUnmount. It's crucial to remove event listeners in componentWillUnmount since many React with JQuery plugins bind them to the DOM. If the plugin does not include a cleanup function, we will need to create one on our own, making sure to remove any event listeners the plugin could have registered to prevent memory leaks.

Integration of jQuery Chosen Plugin

Let's create a simple wrapper for the Chosen plugin, which enhances <select> inputs, as a more practical example of these ideas. Let's first see how the DOM is affected by Chosen.

If you use this method on a DOM node with the select attribute, it will read the attributes from the original node, cover it with an inline style, and then append a new DOM node with its visuals directly after the <select>. Then it fires the React with JQuery events, to tell us about the changes.

Let's assume that the API we aim to achieve with our wrapper React component is as follows:

For simplicity, we will use it as an uncontrolled component.

We'll start by building by creating an empty component with a render() method that returns a <select> enclosed in a <div>:

Take note of how we added a new div to the <select> tag. This is required since Chosen will add a new DOM element immediately after the <select> node we provided it. However, <div> never has more than one child in terms of React. In this way, we make sure that the additional DOM node added by Chosen won't clash with React updates. It's crucial to make sure React has no reason to access any DOM nodes if you edit the DOM outside the React flow.

We will then put the lifecycle techniques into action. In componentDidMount, we must initialise Chosen with a reference to the <select> node, then in componentWillUnmount, we must destruct it.

Keep in mind that the this.el field has no special importance according to to React. It only functions because, in the render() method, we previously allocated this variable from a ref:

Our component will render as a result of this, but we want to also be informed when a value changes. This will be accomplished by subscribing to the jQuery change event on the Chosen-managed <select>.

Due to the possibility that the component's props, including event handlers, could change over time, we won't give this.props.onChange straight to Chosen. As an alternative, we'll create a handleChange() method which will call this.props.onChange and subscribes to the jQuery change event:

Finally, there is just one last step to take. Props in React can vary over time. If the parent component's state changes, the <Chosen> component, for instance, may get different children. Therefore, we must manually update the DOM at integration points as soon as a prop is updated since we're no longer using React to handle DOM management.

According to the documentation for Chosen, we can use the jQuery trigger() API to let it know when the original DOM element has changed. Updates to this.props.children inside <select> will be handled by React, but we'll also provide a componentDidUpdate() lifecycle function which alerts Chosen to changes in the list of children:

From doing this, Chosen will be informed when the <select> children are changed which is managed by React and when to refresh its DOM element.

The Chosen component has been fully implemented as follows:

Integrating with the other View Libraries

React can be integrated into various applications because of the flexibility of ReactDOM's render() method.

ReactDOM's render() method can be called numerous times for separate UI elements, which can range in size from a little button to a major application. 

This is how React is used on Facebook. This enables us to put the React applications together and combine them with our current client-side code and server-generated templates.

Integrating React in a Backbone View

The data for the DOM elements in backbone views are often created using HTML strings or template methods that produce strings. The rendering of a React component might replace the use of this procedure as well.

We'll make a Backbone view called ParagraphView in the section below. To render a React Paragraph component into the DOM element, it will override the render() function of Backbone (this.el). We again use ReactDOM.createRoot() here:

We must also use root.unmount() in the remove function to ensure that React unregisters any event handlers and resources connected with the component tree.

Since we are removing the entire tree by hand, we need to call this method because cleanup is automatically performed when a component is removed from within a React tree.

Using Model Layers to Integrate

Several frameworks and libraries can build model layers for React components. However, it is generally recommended that they use unidirectional data flow like React state, Flux, or Redux.

Using Backbone Models in React Components

By listening to the various change events and manually forcing an update, it is the easiest way to consume Backbone models and collections from the React component.

Model rendering components would listen for change events, whereas collection rendering components would listen for add and remove events. The component can be rerendered with the updated data using forceUpdate().

In the example that follows, a Backbone collection is rendered by the List component, with individual items being rendered by the Item component.

Extracting Data from Backbone Models

According to the method described above, your React components must be familiar with the idea of the Backbone models and collections.

A solution to this is to keep the logic in one place by extracting the attributes of the model as plain data whenever they change.

All attributes from a Backbone model are extracted by a higher-order component into the state before being passed on to a wrapped component.

In the example below, we will create the initial state by copying the model's attributes. The state update is triggered by the change event (which we unsubscribe from on unmounting), and the model's current attributes are updated when it occurs. Also, we make sure that we unsubscribe from the old model when the model prop itself changes, and subscribe to the newly created one.

Although this example doesn't cover everything there is to know about working with Backbone, it will give you a general idea:

As an example, we will connect a React component named NameInput to a Backbone model and update an attribute called firstName that will change whenever the input changes:

There are other applications of this technique besides Backbone. The React lifecycle methods can be subscribed to by any model library and the data can be copied into the local state by optionally.

Conclusion

  • There are numerous JavaScript or ReactJS libraries available, such as toastify, UUID, etc.
  • You can create a React application by following some basic steps and then installing the library.
  • React ignores changes to the DOM done outside of the framework. So, to prevent conflicts we must stop the component from updating.
  • Preventing conflicts can be achieved by rendering components, like an empty div, that is not updated by React.
  • The aim of the article is to integration with jQuery and Backbone, although the same principles may be used to integrate components with any existing code.
  • The easiest way to consume Backbone models and collections from the React component is by listening to the various change events and manually forcing an update.
  • It's crucial to remove event listeners in componentWillUnmount since many jQuery plugins bind them to the DOM.