Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I safely do DOM operations in a React application, but outside the React component?

Tags:

reactjs

I'm getting ready to do my first React project, and my reading has made it pretty clear that I need to let React handle all rendering with the virtual DOM, and that I shouldn't do any manual DOM operations that would interfere with the virtual DOM calculations.

What I can't figure out, however, is this:

Suppose that I have a React component rendered in div #app in a page with other HTML. Does this mean that I have to refrain from any ordinary JavaScript DOM operations anywhere on the page? Or can I safely use DOM operations elsewhere on the page as long as I leave the #app div and elements inside the actual React component alone?

EDIT: Motivating use case

My reason for considering having non-React components manipulate the DOM outside of the React component is mostly so that the HTML can be seen by Google without jumping through a lot of hoops. Suppose that I wanted some descriptive text about the app that would be useful for SEO, and that description might have some dropdown toggles, etc. (hence the DOM issue). Would I really want/need to write everything in React just because the complex UI of the app itself uses React, if the cost is making some text hard for Google to index?

like image 774
DLH Avatar asked Sep 20 '16 19:09

DLH


2 Answers

Assuming your html file looks like this:

<body>
  <div id="app"></div>
  <div id="others"></div>
</body>

and React is initialized like this:

ReactDOM.render(<Component/>, document.getElementById('app'));

you can safely modify div#others and any parts of the DOM except inside div#app as it is managed by React.

like image 173
Yangshun Tay Avatar answered Dec 29 '22 07:12

Yangshun Tay


I may be misunderstanding your question, but React would be a great candidate to handle all of your DOM "operations".

Your React components can live on the same page as elements that are manipulated with run-of-the-mill JS DOM operations, but you are introducing conflicting paradigms. If you ever think to yourself "I can't do this in React, but I know how to with jQuery", you are most likely missing something.

EDIT: Thanks for clarifying the use case. You definitely don't need to write everything in React. As others have said, I would advise you to leave the part of the DOM owned by React alone with your other JS. Fetch as Google looks like it could be helpful for exploring SEO in React.

like image 45
Rand Avatar answered Dec 29 '22 07:12

Rand