Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • Can I rely on React ignoring DOM nodes I've added side by side with React DOM nodes inside a React tree? — I understand that the non-React nodes will be removed, if React decides to remove the node into which I inserted them. This is fine with me. But I do wonder if React some day in the future will get upset on these additional nodes not managed by React, and refuse to work?

  • If React doesn't manage any styles of a DOM node (I haven't added any style attribute to the nodes generated by render()), then can I via jQuery safely add my own styles to this DOM node? E.g. look up a node by #id in jQuery and then set its width.

  • If there's no className on a DOM node generated by React, can I then safely via jQuery add and remove classes to this node? (For example, add a class on mouse hover.)

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.

like image 505
KajMagnus Avatar asked Dec 25 '14 10:12

KajMagnus


1 Answers

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.

like image 187
Brigand Avatar answered Nov 29 '22 09:11

Brigand