Created
May 26, 2019 09:06
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
); |
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.
Thanks man this helped.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note to self: some examples are using
const $ = window.$
. In your next app, if the above code didn't function properly, addconst $ = window.$