KajMagnus
KajMagnus

Reputation: 11686

Is it okay to do all these jQuery things to a React.js DOM tree?

I recently started using React and Flux for a project of mine, and I'm using jQuery too, for some parts of the GUI. Via jQuery, I sometimes add CSS classes and styles and even DOM nodes to elements created and updated by React. This seems to work just fine. React doesn't complain, and, when render() re-runs, React doesn't modify the classes and styles and the DOM nodes that has been added somewhere deep inside a react root.

One reason I'm currently doing these possibly weird things, is that I have some jQuery soup legacy code that I don't want to port to React right now. Another is that I'm using some jQuery plugins that sometimes add DOM nodes inside the React tree.

Upvotes: 6

Views: 1894

Answers (1)

Brigand
Brigand

Reputation: 86260

That sounds fine, but there are some rules you need to follow (and you can only use plugins that follow these rules):

  • don't remove/replace/move any nodes React creates
  • don't create siblings to React nodes, especially between or before react nodes
  • do create nodes, add event listeners, modify dom in componentDidMount and/or componentDidUpdate
  • do remove nodes, remove event listeners, in componentWillUnmount
  • do create and append nodes manually in componentDidMount to pass to jQuery plugins
  • don't modify DOM outside of react components
  • do pass a callback to setState (argument 2) to do something after react updates it (but prefer componentDidUpdate)

For manually mounted React components (via React.render)

  • don't mount a react component as a child of a plugin controlled element with no lifecycle hooks
  • do use React.unmountComponentAtNode to clean up React components before removing their parent from the DOM
  • do pass a callback to React.render (argument 3) if you must do something after the component is mounted

Please edit the question if I missed anything, or included a rule you feel is invalid.

Upvotes: 13

Related Questions