How to integrate jquery plugin in react functional component

5.2k views Asked by At

I am developing an app using functional React component with react hook. I integrate jquery in my app following the code:

    import React, {useEffect} from 'react'
    import $ from 'jquery'
    window.jquery = window.$ = $
    function App(){
    useEffect(() => {
     if($){
        $('#btn').click(e=>{
           $('#txt').hide()
        })
      }
    },[$])
    
    return (
        <button id='btn'>Click </button>
        <p id='txt'> 
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when 
            an unknown printer took a galley of type and scrambled it to make a type specimen 
            book. 
        </p>
    )

This code perfectly works for me. But I can not add any external plugin as chosen. Please give me an idea to add a jquery plugin to my app. I used create-react-app command.

1

There are 1 answers

0
adeelsafdar On

@stminion001 hooks allow us to achieve this functionality. You can integrate datatables.net using this approach. To add package in dependencies: npm install jquery datatables.net

    import React, {useEffect, useRef} from 'react';

    const $ = require('jquery');
    $.DataTable = require('datatables.net');

    const CustomDataTable = (props) => {
      
      const myTable = useRef(null);

      // componentDidMount
      useEffect(() => {
        // fill columns according to your data
        $(myTable.current).DataTable({
          data: props.data,
          'columns': [
            {title: 'first col'},
            {title: 'second col'},
            {title: 'third col'},
            ....
          ]
        });
      }, []);

      useEffect(() => {
        // componentWillUnmount
        return () => {
          $(myTable.current).DataTable().destroy();
        }
      }, []);

      return (
        <React.Fragment>
          <table className='display' width='100%' ref={myTable}>

          </table>
        </React.Fragment>
      )
    }

    export default CustomDataTable;