About
React is unaware of changes made to the DOM outside of React therefore to integrate DOM manipulation library such as Jquery, React should be prevented from updating the component
To prevent React from updating the DOM after mounting, we will return an empty <div /> from the render() method with:
- no properties
- or children
- The chosen component
class Chosen extends React.Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.chosen(); // activate chosen
}
// Many jQuery plugins attach event listeners to the DOM so it’s important to detach them in componentWillUnmount.
// If the plugin does not provide a method for cleanup, you will probably have to provide your own, remembering to remove any event listeners the
componentWillUnmount() {
this.$el.chosen('destroy');
}
render() {
return (
<div>
<select ref={el => this.el = el}>
{this.props.children}
</select>
</div>
);
}
}
- A component using chosen
function Example() {
return (
<Chosen onChange={value => window.console.log(value)}>
<option>vanilla</option>
<option>chocolate</option>
<option>strawberry</option>
</Chosen>
);
}
- The Render function gets the App function as input argument
ReactDOM.render(
<Example />,
document.getElementById('root')
);
- The standard div root element placeholder
<div id="root"></div>