Home > Enterprise >  How can I Inject jQuery tooltip code into React via NPM or Hook?
How can I Inject jQuery tooltip code into React via NPM or Hook?

Time:05-20

jQuery code is injected in the root file of react project and now it needs to use via NPM package any help/suggestion?

<script>
$(document).ready(function() {
    $("body").tooltip({ selector: '[data-bs-toggle=tooltip]', trigger : 'hover', html:true });
});
function hideTooltip() {
    $(".tooltip").hide();
}
</script>

CodePudding user response:

You don't. It is not recommended to use jQuery inside of a react application.

As React states in its documentation :

"Just because it’s possible, doesn’t mean that it’s the best approach for React apps. We encourage you to use React components when you can. React components are easier to reuse in React applications, and often provide more control over their behavior and appearance."

You can achieve this by simply using CSS (:hover & adjacent sibling selector)

You can also use a library which will do the trick for you, no need to reinvent the wheel

Here is a code sample to illustrate my words :

.tooltip-container {
  padding: 1rem;
  position: relative;
}

.tooltip-content {
  opacity: 0;
  visibility: hidden;
  
  background: #333;
  padding: 5px 10px;
  color: #fff;
  
  position: absolute;
  top: 0;
  left: 0;
  
  transition: all 0.3s;
}

.tooltip-hoverable:hover   .tooltip-content {
  opacity: 1;
  visibility: visible;
}
<div >
  <p >
    Hover me
  </p>
  <span >I'm the tooltip</span>
</div>

CodePudding user response:

you could use import $ from 'jquery'; and useEffect/componentDidmount

import { createRoot } from 'react-dom/client';
import TodoList from './refs/TodoList';
import { useEffect } from 'react';
import $ from 'jquery';

const App = () => {
    useEffect(() => {
        $("body").tooltip({ selector: '[data-bs-toggle=tooltip]', trigger : 'hover', html: true });
    }, []) 

    return (
        <div>
            <TodoList />
        </div>)
};

const container = document.getElementById('root');
const root = createRoot(container!);
root.render(<App />);
  • Related