How can I incorporate Chosen into my React project?

孤街醉人 提交于 2019-12-12 15:04:00

问题


I want to use a jquery plugin Chosen in my project. I installed jQuery and Chosen via npm:

npm i jquery chosen-js -S

Both libraries are now in my node_modules folder. Unfortunately I keep getting an error: ReferenceError: jQuery is not defined when the app tries to compile.

Here is where I make a call to the Chosen library:

import React from "react";
import ReactDom from "react-dom";
import $ from "jquery";
import "chosen-js/chosen.css";
import "chosen-js/chosen.jquery.js";

class App extends React.Component {
  componentDidMount() {
    $(this.refs.list).chosen();
  }

  render() {
    return (
      <select ref="list">
        <option>vanilla</option>
        <option>chocolate</option>
        <option>strawberry</option>
      </select>
    );
  }
}

ReactDom.render(, document.getElementById("app"));

Here's a pic of the error:


回答1:


don't change sources, better write in your component

window.jQuery = require('jquery');

before chosen-js imports




回答2:


I answered your question on Udemy as well. If you do really wanna take your react career seriously, you need to eventually quit using jQuery.

I have made very complex select components, ones that even use data from APIs, using react-select. I would suggest using React Select for all your selection needs, it's a powerhouse component and will change your life.

If you still find it imperative to use chosen.js, then edit 'chosen-js/chosen.jquery.js' and add import statements or require statements like

import jQuery from 'jquery' // or
const jQuery = require('jquery');

so that the reference error goes away. However, if you consider a serious front end career you need to understand that jQuery is dead, and serious apps will not use both react and jquery for the simple question of bloating and redundancy



来源:https://stackoverflow.com/questions/45664351/how-can-i-incorporate-chosen-into-my-react-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!