Home > Software engineering >  selectize.js typescript: Cannot read properties of undefined (reading '0')
selectize.js typescript: Cannot read properties of undefined (reading '0')

Time:07-18

I am trying to implement selectize.js inside my project with webpack and typescript.

First I installed selectize.js and related types:

yarn add @selectize/selectize 
yarn add @types/select2 

In my code I inserted this:

require("selectize")();

jQuery(function($){

    $(document).ready(function(){

        $('.classic-select').selectize();
    
    });
    
});

The code compiles correctly but when I go to run it in console I get this error and I don't understand what it refers to:

Cannot read properties of undefined (reading '0')

Can you help me solve this problem?

Thanks in advance Danilo

CodePudding user response:

After several attempts, I figured out how to correctly implement selectize.

First I imported jquery and selectize like this:

import $ from 'jquery';
import 'selectize'; // globally assign select2 fn to $ element

Next I used selectize

jQuery(function($){

    $(document).ready(function(){

        (<any>$('.classic-select')).selectize();
    
    });
    
});

You can also implement it like this

$(() => {
    (<any>$('.classic-select')).selectize();
});

If you compile the code the jquery library will also be imported. If jquery has already been called in your code you can exclude it from compiling through webpack:

externals: {
  jquery: 'jQuery'
}

I hope it will be useful!

  • Related