简体   繁体   中英

TypeError: jquery__WEBPACK_IMPORTED_MODULE_1___default(...)(...).select2 is not a function

I want to use select2 jquery library in my react js web application

i am import jquery in index.html page

<script type="text/javascript" src="%PUBLIC_URL%/assets/js/select2.min.js"></script>

here select2.js component

 import React,{useState ,useEffect,useRef, Component} from 'react';
 import $ from 'jquery';

export default class select2 extends Component
{
   
    componentDidMount() {
        $(this.refskills).select2();
      }  
    render() {
        return (
        <select className="multiple-skils" 
                name="datajobskills" 
                multiple="multipleskils"
                ref ='refskills'>
            <option value="1">HTML</option>
            <option value="2">JS</option>
            <option value="3">CSS</option>
        </select>
        );
    }
      
}

and I am using that import select2 component

import React,{useState ,useEffect,useRef} from 'react';
import axios from 'axios';
import $ from 'jquery';
import Tags from '../services/select2'

const Dashboardcomponent = (props) =>
{ return (
    <div>
<select2></select2>
</div>
)
}

Like others have suggested in the comments, it's not best practice to use jQuery with React since jQuery manipulates the DOM directly and React is unaware of those changes. React only knows about it's own representation of the DOM within the virtual DOM so it's best to avoid using them together. If you want you can take a look at this package react-select ( https://react-select.com/home ) that does pretty much what you want but in a react way of doing things.

With that said, if you need your solution to work , instead of using the jquery package and importing it into the DashboardComponent , you could add it as a global script in your index.html - just like you've done with the select2 script. Then you can use it like so in your componentDidMount method - window.$(".multiple-skils").select2();

Here's working example - https://codesandbox.io/s/cool-greider-koezs?file=/src/select2.js:120-158

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM