DEV Community

loading...

React - Integrating with Third-Party Libraries

bewarusman
I write computer programs
・5 min read

Alt Text

Summary

In this post, I will try to explain React - Integration with third-party libraries.

Introduction

React.js open-source javascript library for building front-end applications. According to StackOverflow 2020 survey, it is the second most popular web framework after JQuery and the most wanted web framework in the industry.

There are many libraries that are written in plain Javascript or as a JQuery plugin, an example is Datatable.js. There is no need to reinvent the wheel, consume a lot of time and energy, and re-create those libraries.

When I started working on React.js last year, I faced a big problem. Integrating React.js with other libraries is not easy and straight-forward. Also, it is not very difficult to integrate with other libraries.

React.js has good documentation but it has only one example. It teaches how to integrate with the JQuery Chosen library. I found out that not all libraries can be integrated using the same technique as documented. There are some other techniques, developers need to know and use to integrate with some other libraries.

Class Components

Third-party libraries can be integrated with class components, also with functional components using Hooks. According to Dan Abramov, they (React Team in Facebook) have no plans to remove ES6 class syntax support in the future. I have poor information about Hooks, that is why I am using class components in the examples.

A React.js component may update the DOM elements multiple times during its lifecycle after component props or states update. Some libraries need to know when the DOM is updated. Some other libraries need to prevent the DOM elements from updating.

Usually, component state variables change when a normal user interacts with the component such as pressing a button. This can be achieved using this.setState function. Props are used to pass data from the parent component down to the child component.

Sometimes, we need to fetch data from the server and the data is read after the component is mounted on (written to) the DOM. Accordingly, the component updates the DOM when the data is finished fetching from the server either updating States or Props.

A class component is an ES6 class that extends React's Component.

// This is a basic class component which only displays message in h1 tag.
import React from "react";

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Refs

React provides a way for developers to access DOM elements or other React elements. Refs are very handy when integrating with third-party libraries.

import React from "react";

class Datatable extends React.Component {
  render() {
    return (
      <table ref={(el) => (this.el = el)}>
      </table>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

React Lifecycle Methods

We need to know some lifecycle methods. These lifecycle methods are important for initializing other libraries, destroying components, subscribing and unsubscribing events

1- componentDidMount: it is fired when the element is mounted on the DOM. It is like jquery's $(document).ready().
Usage:

  • fetching data from the server.
  • initializing third-party libraries.
componentDidMount() {
  this.$el = $(this.el);
  this.currentTable = this.$el.DataTable({});
}
Enter fullscreen mode Exit fullscreen mode

3- componentDidUpdate: it is fired when the props passed to the component are updated or the method this.setState is called to change the state of the component. This method is not called for the initial render().
Usage:

  • reload third-party library if props is updated.
componentDidUpdate(prevProps) {
  if (prevProps.children !== this.props.children) {
    // update third-party library based on prop change
  }
}
Enter fullscreen mode Exit fullscreen mode

3- componentWillUnmount: it is fired before the React component is destroyed and unmounted on the DOM.
Usage:

  • Unsubscribing from events
  • Destroying third-party library
componentWillUnmount() {
}
Enter fullscreen mode Exit fullscreen mode

4- shouldComponentUpdate: it is used to avoid the React component from re-rendering. It prevents to update the DOM even if the state or props are updated.
Usage:

  • Some libraries require an un-changeable DOM.
shouldComponentUpdate() {
  return false;
}
Enter fullscreen mode Exit fullscreen mode

Setup

We use create-react-app boilerplate to set up a React.js project using. The bellow will create React.js app and then start it.

npx create-react-app react-integrations
cd react-integrations
npm start
Enter fullscreen mode Exit fullscreen mode

We will remove the application from unwanted files that comes with the boilerplate like index.css, app.css, and logo.js.

Datatables - Integrations

Datatables.js is a free JQuery plugin that adds advanced controls to HTML tables like searching, sorting, and pagination.

  • Need to install a couple of dependencies from npm: jquery and datatables.net
npm i -S jquery datatables.net
Enter fullscreen mode Exit fullscreen mode
  • Add a link to DataTable.css file in index.html.
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css" />
Enter fullscreen mode Exit fullscreen mode
  • Create a class component named DataTable inside components/DataTable.js.

  • Import the libraries:

var $ = require("jquery");
$.DataTable = require("datatables.net");
Enter fullscreen mode Exit fullscreen mode
  • Inside the render() method, we need to have a table element with a ref. It looks like an html ID, we use it for selecting (referencing) it.
  • We need to render children props inisde the tbody which is passed by the parent element.
render() {
  return (
    <table ref={(el) => (this.el = el)}>
      <thead>
        <tr>
          <th>#</th>
          <th>Title</th>
          <th>Completed</th>
          <th></th>
        </tr>
      </thead>
      <tbody>{this.props.children}</tbody>
    </table>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • Inside the componentDidMount() method, we need to get the ref and call jquery method DataTable()
componentDidMount() {
  this.$el = $(this.el);
  this.currentTable = this.$el.DataTable();
}
Enter fullscreen mode Exit fullscreen mode
  • Inside the componentDidUpdate(prevProps), we refresh the datatable by calling ajax.reload() when the props are updated. According to datatable.js, this method refreshes the table.
componentDidUpdate(prevProps) {
  // It means that only when props are updated
  if (prevProps.children !== this.props.children) { 
    this.currentTable.ajax.reload();
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Finally, inside componentWillUnmount() we destroy the table.
componentWillUnmount() {
  this.currentTable.destroy();
}
Enter fullscreen mode Exit fullscreen mode
  • Using the DataTable component in our react application.
import React from "react";
import DataTable from "./components/DataTable";

class App extends React.Component {
  state = {
    todos: [],
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((data) =>
        this.setState({
          todos: data,
        })
      );
  }

  render() {
    return (
      <DataTable>
        {this.state.todos.map((todo) => (
          <tr key={todo.id}>
            <td>{todo.id}</td>
            <td>{todo.title}</td>
            <td>{todo.completed ? "Yes" : "No"}</td>
            <td>
              <button>Edit</button>
              <button>Delete</button>
            </td>
          </tr>
        ))}
      </DataTable>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Conclusion

We have learnt how to use a third-party library like DataTable.js inside React.js. I have plans to post more examples in the future like select2. Please comment below and mention the name of the libraries if you like me to post about.

Discussion (1)

Collapse
pratiksharm profile image
Pratik sharma

can you explain how can i do the same with react hooks? using third party libraries with react hooks??