FAQ: Intro to JSX - The Virtual DOM

This community-built FAQ covers the “The Virtual DOM” exercise from the lesson “Intro to JSX”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Learn ReactJS: Part I

FAQs on the exercise The Virtual DOM

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

What is this expression anyway?

const hello = <h1>Hello world</h1>;

// This will add "Hello world" to the screen:
root.render(hello, document.getElementById('app'));

In all previous exercises, we used a notation like:

const root = createRoot(container);
root.render(toDoList);

How can we apply the render() method to root if we don’t even have root defined?

Okay, let’s assume this is a continuation of the previous exercise and we have root designated. But why do we use the second argument document.getElementById('app') in .render()? The root variable already contains the root to this element with the id ‘app’.

You could just write:

const hello = <h1>Hello world</h1>;
root.render(hello);
2 Likes

Seems to be a mistake. You can give feedback to the course authors and then perhaps they will fix it. You can select “Get Unstuck > Bugs > There’s an issue with the content” and report the issue in the exercise.

The explanation isn’t showing the whole code, so we can assume that the container and root have already been set up (along with the appropriate imports),

// Not shown in exercise, but we can assume it has already been done.
const container = document.getElementById('app');
const root = createRoot(container);

Then, we can render the JSX in the code snippet of the exercise as,

root.render(hello);

I think the course authors mixed up approaches during updates to the course.

The deprecated way of rendering (see documentation) would have been:

ReactDOM.render(hello, document.getElementById('app'));

That approach does have a second parameter, but you are correct that a second argument is not used in the createRoot and root.render approach.

The course authors probably mixed up the two approaches and forgot to update the exercise explanation correctly.

Links of Interest:

3 Likes