Importing JQuery Plugin – Chosen

Chosen is a jQuery plugin that makes long, unwieldy select boxes much more user-friendly.

Say, we want to use Chosen like this:


RESETRUNFULL
export default function Example() {
  return (
    <Chosen onChange={value => console.log(value)}>
      <option>vanilla</option>
      <option>chocolate</option>
      <option>strawberry</option>
    </Chosen>
  );}

Begin by installing the plugins:

npm install jquery --savenpm install chosen-js --save

Add this in line #1 of node_modules/chosen-js/chosen.jquery.js:


RESETRUNFULL
import jQuery from 'jquery';

To implement the Chosen component:

The key takeaway here is to assign the ref to the DOM node to a JQuery variable.
RESETRUNFULL
import $ from 'jquery';import React from 'react';import "chosen-js/chosen.css";import "chosen-js/chosen.jquery.js";class Chosen extends React.Component {
  componentDidMount() {
    this.$el = $(this.el);
    this.$el.chosen();
    this.handleChange = this.handleChange.bind(this);
    this.$el.on('change', this.handleChange);
  }
  componentDidUpdate(prevProps) {
    if (prevProps.children !== this.props.children) {
      this.$el.trigger("chosen:updated");
    }
  }
  componentWillUnmount() {
    this.$el.off('change', this.handleChange);
    this.$el.chosen('destroy');
  }
  handleChange(e) {
    this.props.onChange(e.target.value);
  }
  render() {
    return (
      <div>
        <select className="Chosen-select" ref={el => this.el = el}>
          {this.props.children}
        </select>
      </div>
    );
  }}