Blog>
Snippets

Integrating with Third-Party Libraries

Use useRef to integrate a third-party DOM library in a React functional component, such as initializing a jQuery plugin on a ref to a DOM node.
import React, { useRef, useEffect } from 'react';
import $ from 'jquery';

function MyComponent() {
  // Create a ref that we will attach to a DOM element
  const myElementRef = useRef(null);

  useEffect(() => {
    // Ensure that the ref is current and the jQuery library is available
    if (myElementRef.current) {
      // Initialize the jQuery plugin on the ref's current DOM node
      $(myElementRef.current).myJQueryPlugin();
    }
  }, []); // Pass an empty dependency array to run only once on mount

  return (
    // Render an element and attach the ref to it
    <div ref={myElementRef} >
      {/* Content goes here */}
    </div>
  );
}

export default MyComponent;
This code snippet demonstrates how to integrate a jQuery plugin with a React functional component using the useRef hook. A reference to a DOM element is created using 'useRef' and it is assigned to a 'div' element in the render method. The 'useEffect' hook is then used to ensure that the DOM element is available and only runs once when the component mounts to initialize the jQuery plugin on that element.