Integrating React with Other Libraries

Introduction 

Any online web application can benefit from React. React can be embedded in other programs, and other applications can be integrated with React with little care. This blog will look at some of the more frequent use cases of integrating React with other libraries, focusing on jQuery and Backbone integration. However, the same principles can be extended to integrating components with any current code.

We'll look at how to integrate with other libraries or include JavaScript libraries in a React app. Facebook created ReactJS, which is a JavaScript library. You may export your components and import them wherever you want in your files with the ReactJS workflow, similar to first importing the thing or component and then using it in your code. There are numerous ReactJS or JavaScript libraries available, such as UUID, toastify, and others. They're simple to incorporate into your ReactJS app.

In the following example, we'll use a JavaScript library called UUID, which is quite popular and provides us with a unique ID string every time we use it, so we don't have to type it in manually.

Creating A React App And Installing Modules:

1: Run the following command to create a React application.

npx create-react-app folderName

 

2: After you've created your project folder (folderName), use the following command to get in there.

cd folderName

 

3: After you've finished building your ReactJS project, run the command below to install the UUID module.

npm install UUID

 

The project structure will be:

folderName
|
-- node_modules
-- src
    |
    -- App.js
-- package-lock.json
-- package.json

 

For example: We will write the code in the App.js file. The App is the default component, where we'll write our code. We will use the v4() function to produce the ID and display it to the user, which varies with each refresh.

import React from "react"
import { v4 } from "uuid"
  
export default function App() {
    const id = v4()
    return (
        <div class="uuidClass">
        <center>
        <p> Your UUID is: </p>
        <p style="font-size:30px;" id="uuid_p">UUID</p>
        <p>Refresh the page to get another</p>
        </center>
        </div>
  )
}

 

Now go to http://localhost:3000/ in your browser, and you should see the following output.

Output

Using DOM Manipulation Plugins

Changes to the DOM(Document Object Model) made outside of React are ignored by React. When another framework modifies the same DOM nodes, React gets confused and has no method of recovering.

This isn't to say that combining React with other methods of manipulating the DOM is impossible or even difficult; you have to be aware of what each does.

Keeping the React component from updating is the most straightforward technique to avoid conflicts. This can be accomplished by rendering elements that React does not need to update, such as an empty <div />.

Way to Avoid Conflict

Let's make a wrapper for a generic jQuery plugin to demonstrate this.

We'll add a reference to the root DOM element. We'll get a reference to it inside componentDidMount so we can provide it to the jQuery plugin.

We'll return an empty <div /> from the render() method to avoid React from touching the DOM after mounting. React does not need to update the <div /> element because it has no properties or children, leaving the jQuery plugin free to manage that part of the DOM:

class SomePlugin extends React.Component {
  componentDidMount() {

  this.$el = $(this.el);
  this.$el.somePlugin();
}
  componentWillUnmount() {

  this.$el.somePlugin('destroy');
}

  render() {

  return <div ref={el => this.el = el} />;
}
}

 

Both the componentDidMount and componentWillUnmount lifecycle methods have been defined. Because many jQuery plugins attach event listeners to the DOM, componentWillUnmount must disconnect them. If the plugin doesn't offer a cleanup method, we'll have to write our own, making sure to remove any event listeners the plugin has registered to avoid memory leaks.

Integration of jQuery Chosen Plugin 

Let's construct a small wrapper for the 'Chosen' plugin, which augments <select> inputs, as an example of these principles.

Note: Just because it's possible does not mean it is the optimum approach for React apps. When feasible, use the React components. React components are more easier to reuse in React apps, and they frequently provide you with more flexibility over how they behave and look.

For simplicity, we'll use an uncontrolled component to implement it.

We'll start by making an empty component with a render() method that returns a <select> wrapped in a <div>. We will then enclose <select> with a second <div>. This is required as ' Chosen' will append another DOM element exactly after the <select> node is passed to it. However, when it comes to React, <div> always has a single child. This is how we make sure that React changes don't conflict with Chosen's extra DOM node. It's critical to guarantee that if you edit the DOM outside of React flow, React has no reason to access those DOM nodes.

The lifecycle methods are implemented next. In componentDidMount, we must initialize 'Chosen' with the ref to the <select> node and break it down in componentWillUnmount.

This is sufficient to render our component, but we also want to be updated when its value changes. We'll do this by subscribing to the jQuery change event on the 'Chosen' by managing <select>.

Because component props, including event handlers, may change over time, we won't provide this.props.onChange straight to Chosen. Instead, we'll create a handleChange() method that calls this.props.onChange and subscribes to the jQuery change event.

Props in React can vary over time. If the parent component's state changes, the <Chosen> component may receive different children. Because we no longer allow React to handle the DOM for us, it's critical that we manually update the DOM in response to prop updates at integration points.

According to Chosen's documentation, we may use the jQuery trigger() API(Application Programming Interface) to alert it to changes to the original DOM element. We'll assign the task of updating this to React. We'll use props.children inside <select>, but we'll also add a componentDidUpdate() lifecycle function to notify Chosen when the children list changes.

Chosen will be notified to update its DOM element when the <select> children managed by React change.

 

This is how the Chosen component is implemented completely:

import React from "react";
import ReactDom from "react-dom";
import "chosen-js/chosen.css";

class Chosen extends React.Component {
  /*
    Here we initialise Chosen with the ref to the <select> node, and 
    break it down in componentWillUnmount.
  */ 
  componentDidMount() {
    this.$el = $(this.el);
    this.$el.chosen();

    this.handleChange = this.handleChange.bind(this);
    this.$el.on('change', this.handleChange);
  }
  
  /*
    This function is a lifecycle method that notifies the Chosen 
    regarding the changes in the children list.
  */
  componentDidUpdate(prevProps) {
    if (prevProps.children !== this.props.children) {
      this.$el.trigger("chosen:updated");
    }
  }
  /*
    This function allows us to execute the code when the component gets 
    destroyed or unmounted from the DOM(Document Object Model).
  */
  componentWillUnmount() {
    this.$el.off('change', this.handleChange);
    this.$el.chosen('destroy');
  }
  
  /*
    handleChange() method calls the this.props.onChange and subscribes 
    it to the jQuery change event.
  */
  handleChange(e) {
    this.props.onChange(e.target.value);
  }

  render() {
    return (
      <div>
        <select className="Chosen-select" ref={el => this.el = el}>
          {this.props.children}
        </select>
      </div>
    );
  }
}

function Example() {
  return (
    <Chosen onChange={value => console.log(value)}>
      <option>rose</option>
      <option>lily</option>
      <option>lotus</option>
    </Chosen>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('root')
);

 

Output

Integrating with the other View Libraries

Due to the flexibility of ReactDOM.render(), React may be integrated into other applications.

ReactDOM.render() can be called multiple times for independent parts of the UI, which can be as small as a button or can be as large as an app. Although React is commonly used at startup to load a single root React component into the DOM, it can also be called multiple times for independent parts of the UI that can be as small as a button or can be as large as an app.

React is utilized in this manner at Facebook. This allows us to assemble together the React applications and blend them with our existing server-generated templates and client-side code.

Integrating React in a Backbone View

Backbone views often provide content for their DOM elements using HTML strings or string-producing template functions. 

Using Model Layers to Integrate

While unidirectional data flow, such as React state, Flux, or Redux, is generally encouraged, React components can leverage a model layer from other frameworks and packages.

Frequently Asked Questions

1. Is it possible to use other libraries within React?

Ans: Any online application can benefit from React, and integrating React with other libraries is possible. This can also be embedded in other programs, and other applications can also be integrated into React with little care.

 

2. What react libraries can we use?

Ans: The React Component Libraries we can use are:-

  • Material UI
  • React-Bootstrap
  • React Router
  • Semantic UI 
  • Blueprint UI
  • Ant Design
  • React Motion
  • Fluent UI

 

3. Mention the steps for integrating React with other libraries.

Ans: We can include by the following ways:-

Option 1: In your index.html file, you can include the third-party libraries.

Option 2: Use npm install <package-name> -S to install the library and import it into necessary project files.

Key Takeaways

In this blog, we went over the concept of integrating React with other libraries. We looked at how to include JavaScript libraries in a React app. We also learned how to use DOM manipulation plugins.  Despite the fact that React manipulates the DOM tree, integrating React with other libraries can be done using third-party libraries and services.We have ample control over the rendering process due to the various lifecycle methods.


Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of integrating React with other libraries in Web Development. 

 

Credits: GIPHY

Happy Developing!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think