Search code examples
javascriptjqueryreactjscolorbox

Adding Colorbox to my ReactJS application creates "jQuery is not defined"


I'm trying to add Colorbox library to my project created with create-react-app. I've installed jquery-colorbox package via npm and added imports in one of my *.js files:

import $ from 'jquery'; // also tried: import jQuery from 'jquery';
import 'jquery-colorbox';

After that, all I'm getting is an error:

ReferenceError: jQuery is not defined

 (anonymous function)
 node_modules/jquery-colorbox/jquery.colorbox.js:1105
  1102 | 
  1103 |    publicMethod.settings = defaults;
  1104 | 
> 1105 | }(jQuery, document, window));
  1106 | 
  1107 | 
  1108 | 

Anyone have any suggestions how to manage with that problem?

Also, the code I want to run with the Colorbox library is something like this:

$(function() {
    $('.colorbox-group' + id).colorbox({
        rel: 'colorbox-group' + id,
        maxWidth: '95%',
        maxHeight: '95%'
    });
});

UPDATE #1

Also... tried with CDN's and added these lines to index.html file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.6.4/jquery.colorbox-min.js"></script>

And run code inside one of JS files of my app: $.colorbox('something');. Result:

TypeError: __WEBPACK_IMPORTED_MODULE_1_jquery___default.a.colorbox is not a function


Solution

  • Solution 1: Using cdn for jquery & jquery-colorbox

    Here is a simple github repository, I have made using reactjs. Hope it helps!

    Solution 2: Using npm packages for jquery & jquery-colorbox

    Here is a github repository using npm packages with react setup. I have also had the same issue that you got for 'jQuery' undefined. The solution is in webpack config by adding a webpack plugin for jQuery. Add this in your webpack-config file: On top first import the webpack:

    let webpack = require('webpack');
    

    and then add this code:

    plugins: [
        new webpack.ProvidePlugin({
          $: "jquery",
          jQuery: "jquery"
        })
    ]
    

    Solution 3: specifically for 'create-react-app'

    Update the import in your app.js file like below:

    import jQuery from 'jquery';
    window.jQuery = jQuery;
    require('jquery-colorbox');
    

    Hope it solves your query.