InterviewSolution
| 1. |
How to use a library like jQuery in React, which interacts directly with DOM? |
|
Answer» Using jQuery in REACT is not recommended as it directly interacts with the DOM and is generally a bad practice. We should always try first to find a React equivalent of the jQuery plugin or WRITE the plugin ourselves. But many times there are plugins, which are only available in jQuery and no other alternative in ReactJS and also very time consuming to write ourselves. In such cases, we can use the method described below. We attach a “ref” element to the root DOM element. Inside componentDidMount, we will GET a reference to it, so that we can pass it to the jQuery plugin. To prevent React from interacting with the DOM after mounting, we will return an empty <div /> from our render() method. The <div /> element has NOTHING, so React will not update it, leaving the jQuery plugin to manage only that PART of the DOM. Also, we will use componetWillUnmount() to unmount the jQuery plugin, after its work with DOM is done. class anotherJqueryPlugin extends React.Component { componentDidMount() { this.$el = $(this.el); this.$el.anotherJqueryPlugin(); } componentWillUnmount() { this.$el.anotherJqueryPlugin('destroy'); } render() { return <div ref={el => this.el = el} />; } } |
|