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>;
}
}
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>
);
}
}
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({});
}
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
}
}
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() {
}
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;
}
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
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
- 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" />
Create a class component named DataTable inside
components/DataTable.js
.Import the libraries:
var $ = require("jquery");
$.DataTable = require("datatables.net");
- 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>
);
}
- Inside the
componentDidMount()
method, we need to get the ref and call jquery methodDataTable()
componentDidMount() {
this.$el = $(this.el);
this.currentTable = this.$el.DataTable();
}
- Inside the
componentDidUpdate(prevProps)
, we refresh the datatable by callingajax.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();
}
}
- Finally, inside
componentWillUnmount()
we destroy the table.
componentWillUnmount() {
this.currentTable.destroy();
}
- 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;
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.
Top comments (1)
can you explain how can i do the same with react hooks? using third party libraries with react hooks??