Where do I find app from document.getElementById('app') that I am rendering into?

Question

Where do I find the document.getElementById('app') that I am rendering onto?

Answer

In the case of this lesson, you can find that clicking onto the folder icon at the top left of the middle panel will display multiple files, clicking on them opens them. If we open index.html we can see that the main tag has the id of app:

...
<body>
  <main id="app"> 
  </main>
	<script src="https://s3.amazonaws.com/codecademy-content/courses/React/react-course-bundle.min.js"></script>
  <script src="/ProfilePage.compiled.js"></script>
</body>
...

In our local projects using create-react-app we will notice that thereis a public/ directory that contains index.html there will commonly be the <body> tag with an id of root which is what React.render() will use for our react components.

10 Likes

A small aside - you can actually rename the ID of the HTML element to whatever you want, as long as you are referencing the correct ID from the index.html file’s element. Similarly, you can have multiple named elements in the index.html file that, as long as each has a different ID, can have different React pieces inside of each one. Usually you just have a single element as the top-level item, but it is possible to do it this way if you have a good reason to keep pieces separate and non-interacting…

8 Likes

Hello @axelkaban

In my local project usign “create-react-app”, I can see my body and the class “root” but where is located the equivalent of “ProfilePage.compiled.js” of this lesson ? How the link between “index.html” and “App.js” is generated ?

Thank you

Thanks so much for this answer. I was getting really confused as to what ‘app’ in getElementById related to.

I’m curious in finding out if there is some optimization that can be done by having multiple pieces of react injected in HTML. For example, if I have deep nesting, wouldn’t my virtual DOM take longer to render the last child elements of my tree? Would it be better to let the virtual DOM have more breadth than depth?

1 Like

Hi @dreadpeng ,
When the React app is running on the web browser, it creates a DOM first, and that DOM has all the elements, div(s), and their attributes structured in a tree like hierarchical structure and that root element sits on the very top of it. This means, when you say getElementById, DOM knows(In this case ReactDOM that is responsible) that there is one and only one unique ID because IDs are unique. App.js is basically a JSX and will eventually be translated into HTML for the browser to understand. This way, APP.js’s getElementById() looks for a unique ID in the DOM and that is how the link is created.