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:


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:

Installing jQuery and the Chosen plugin via npm
npm install jquery --savenpm install chosen-js --save

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


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.
import $ from 'jquery';
import React, { useEffect, useRef } from 'react';
import "chosen-js/chosen.css";
import "chosen-js/chosen.jquery.js";

function Chosen({ children, onChange }) {
  const selectRef = useRef(null);
  const $elRef = useRef(null);
  const isFirstRender = useRef(true);
  const onChangeRef = useRef(onChange);
  onChangeRef.current = onChange;

  useEffect(() => {
    const $el = $(selectRef.current);
    $elRef.current = $el;
    $el.chosen();
    const handleChange = e => onChangeRef.current(e.target.value);
    $el.on('change', handleChange);
    return () => {
      $el.off('change', handleChange);
      $el.chosen('destroy');
    };
  }, []);

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    $elRef.current.trigger("chosen:updated");
  }, [children]);

  return (
    <div>
      <select className="Chosen-select" ref={selectRef}>
        {children}
      </select>
    </div>
  );
}