React - Jquery

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

Jquery integration in React

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:

  • 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>

2 - Documentation / Reference

Advertising
web/javascript/react/jquery.txt · Last modified: 2019/06/21 09:34 by 108.162.246.129