Skip to content

Instantly share code, notes, and snippets.

@danielnunez
Forked from imedadel/index.js
Created April 14, 2021 18:10
Show Gist options
  • Save danielnunez/8f269c53da05d8811177750d29940444 to your computer and use it in GitHub Desktop.
Save danielnunez/8f269c53da05d8811177750d29940444 to your computer and use it in GitHub Desktop.

Revisions

  1. @imedadel imedadel created this gist May 26, 2019.
    85 changes: 85 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@

    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')
    );