0

I'm trying to use the jquery auto-complete plugin in a React component. I've installed the plugin using npm install jquery-autocomplete --save

Next I try to use the plugin like this in my React component:

import React, { Component } from "react";
import jQuery from "jquery";
// import $ frmom 'jQuery';
import autocomplete from "jquery-autocomplete";

class AutoComplete extends Component {
  componentDidMount() {
    this.refs.autoCompleteInput.autocomplete({
    source: ["aaa", "aab", "aac", "abb", "bbb"]
    });
  }

  state = {};

  render() {
    return <input ref="autoCompleteInput" />;
  }
}

export default AutoComplete;

When using this code, I get this error messages ReferenceError: jQuery is not defined.

What do I need to do so I can use the jQuery plugin?

Edit: I've also tried these lines without success:

//import { jQuery } from "jquery"; import "jquery";

Martijn
  • 24,441
  • 60
  • 174
  • 261
  • I think the proper way to import jQuery is: `import { jQuery } from 'jquery';`– see https://stackoverflow.com/questions/34338411/how-to-import-jquery-using-es6-syntax. That will probably not help with the plugin though, I suspect that will expect jQuery to be available in the global scope, so you'll have to do some webpack magic, this might help: https://stackoverflow.com/questions/29080148/expose-jquery-to-real-window-object-with-webpack – Patrick Hund Aug 04 '18 at 13:32
  • 1
    You're not using `jQuery` import and it's not included into a bundle. Most jQuery plugins expect a global to be there, this depends on a plugin. It likely should be `import 'jquery'`. Please, let know if this works. I'd personally advise against using jQuery autocomplete, there's a bunch of React components. – Estus Flask Aug 04 '18 at 13:33
  • @estus See my updated answer. – Martijn Aug 04 '18 at 13:40
  • See https://stackoverflow.com/questions/29080148/expose-jquery-to-real-window-object-with-webpack . This likely solves the problem. – Estus Flask Aug 04 '18 at 13:43

0 Answers0