0

In my app I import jquery in my index.js and save it on window in order to make it global like this:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import $ from "jquery/dist/jquery.slim.min";
import bootstrap from 'bootstrap/dist/js/bootstrap.min'
window.jQuery = window.$ = $;

ReactDOM.hydrate(<App />, document.getElementById('root'));

On another file i'm trying to use jquery in this way:

useEffect(() => {
    const audio = document.getElementById("player"); 
    const popover = <div>bla bla bla</div>
    $('#player').popover({title: popover, html: true, placement: "bottom"}); 
})

but I get an error that '$' is not defined. Why it isn't becoming global?

Ohad Yeahhh
  • 191
  • 1
  • 10
  • Did you try using ``window.$`` instead? Ecmascript modules scopes everything locally unless you refer them from global object like window – Sachin Singh Mar 12 '21 at 18:37
  • @SachinSingh yes I did. but then I get 'window.$ is not a function' – Ohad Yeahhh Mar 12 '21 at 18:39
  • 2
    Why do you want to set $ on window? You should import $ inside any of your files and use it as a ES module instead. Or if you want global jQuery reference for any reason then add a separate script tag and use the CDN version. – Sachin Singh Mar 12 '21 at 18:43
  • @SachinSingh if I use it in every module, I get an error saying "jquery_dist_jquery_slim_min__WEBPACK_IMPORTED_MODULE_4___default(...)(...).popover is not a function". I can try to import it via script tag, but I want all external global libraries to be administrated with imports in one place and bundle it in one file – Ohad Yeahhh Mar 12 '21 at 18:55
  • @SachinSingh and I also want to know why this doesn't work :) – Ohad Yeahhh Mar 12 '21 at 18:56
  • Hmm! Not sure what the problem is. I tried it myself and it seems to work. Can you check this thread: https://stackoverflow.com/questions/37452086/what-is-the-best-way-to-load-bootstrap-with-an-es6-import This should hopefully solve your problem – Sachin Singh Mar 12 '21 at 19:32
  • If above solution doesn't work. Would you mind sharing a sample code of what you're trying to do. A small repo would work. – Sachin Singh Mar 12 '21 at 19:36

0 Answers0