user7902157
user7902157

Reputation:

React Error : __WEBPACK_IMPORTED_MODULE_4_jquery___default(...)(...).modal is not a function

I'm working on a react project with Bootstrap 4. Bootstrap has been imported through CDN.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

what I wanted is to show/hide a modal if a condition is satisfied. I have already imported jquery also using

npm install jquery --save

in component

import $ from 'jquery'; <-to import jquery

$('#addSupModal').modal('show'); <- to show modal

but during the execution time when the above line gets executed, it shows an error like

Unhandled Rejection (TypeError): __WEBPACK_IMPORTED_MODULE_4_jquery___default(...)(...).modal is not a function

I read about this error and it says maybe because jquery is imported twice with CDN and npm. I don't know for sure what the reason. But I also tried importing jquery from only one method but it doesn't work. Any suggestions?

Upvotes: 9

Views: 18504

Answers (1)

connexo
connexo

Reputation: 56744

Your import import $ from 'jquery' creates a local variable named $ inside your module, which then gets used by $('#addSupModal').modal('show') (instead of the global $ you wanted).

The quickest fix would be to explicitly use the jQuery $ from the global context (which has been extended with your $.modal() because you referenced that in your script tag when you did <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>):

window.$('#addSupModal').modal('show')

It would be better though to not include the jQuery and plugins with script tags at all, because that way you are creating implicit dependencies (which is, your module cannot run without those script tags). Instead, import Bootstrap as well:

import $ from 'jquery'; // <-to import jquery
import 'bootstrap';

$('#addSupModal').modal('show'); // <- to show modal

Upvotes: 32

Related Questions