Skip to content

Instantly share code, notes, and snippets.

@imedadel
Created May 26, 2019 09:06
Show Gist options
  • Save imedadel/6225406e6ddd9e116718f5777f00eb19 to your computer and use it in GitHub Desktop.
Save imedadel/6225406e6ddd9e116718f5777f00eb19 to your computer and use it in GitHub Desktop.
An example of using React Hooks with jQuery and Chosen plugin. `Chosen` is the original example using a class and `Chosed` is the "modern" approach using functions and hooks.
const Chosed = (props) => {
const elmt = React.useRef()
React.useLayoutEffect(()=>{
const $elmt = $(elmt.current)
const handleChange = (e) => {
props.onChange(e.target.value);
}
$elmt.chosen()
$elmt.on('change',handleChange)
$elmt.trigger("chosen:updated")
$elmt.trigger("chosen:updated")
return () => {
$elmt.off('change', handleChange);
$elmt.chosen('destroy');
console.log("unmounted")
}
}, [props.children])
return (
<div>
<select className="Chosen-select" ref={elmt}>
{props.children}
</select>
</div>
)
}
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>
);
}
}
function Example() {
return (
<>
<Chosen onChange={value => console.log(value)}>
<option>vanilla</option>
<option>chocolate</option>
<option>strawberry</option>
</Chosen>
<Chosed onChange={value => console.log(value)}>
<option>vanilla</option>
<option>chocolate</option>
<option>strawberry</option>
</Chosed>
</>
);
}
ReactDOM.render(
<Example />,
document.getElementById('root')
);
@imedadel
Copy link
Author

Note to self: some examples are using const $ = window.$. In your next app, if the above code didn't function properly, add const $ = window.$

@imedadel
Copy link
Author

Another note: If you face jQuery is not defined no-undef in a jQuery plugin that you're using, you'll have to edit the source code of that plugin and add import jQuery from 'jquery'.

Also, note that if the error message is $ is not defined no-undef, then you'll have to add import $ from 'jquery' to your plugin's source code.

@Ericokim
Copy link

Thanks man this helped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment