Is this how you nest React components?

I tried submitting this as my solution for the component nesting React challenge but it made my browser tab crash:

<ParentComponent>
<ChildComponent />
</ParentComponent>

Now every time I try to access the challenge page, the tab freezes and crashes.

I’ve given up trying to make the challenge work so I just wanna know if that’s how you nest components.

Yes, assuming that ParentComponent has been written as a compositional component, which is a little more advanced.

A more common way (at least in the beginning) is to put the child component in the definition of the parent, like this:

class ChildComponent extends React.Component {
  render() {
    return (
      <h3>... and this is the child.</h3>
    )
  }
}

class ParentComponent extends React.Component {
  render() {
    return (
      <div>
        <h1>This is the parent.</h1>
        <ChildComponent />
      </div>
    )
  }
}

On something like codepen they will be in one file, but if you are developing locally those will probably be in different files.

Here is a pen showing this example.

2 Likes

Thanks for the super in-depth answer! The challenge didn’t really do a good job at explaining nesting… I kinda understand why it keeps freezing and crashing now lol

There are ways to accomplish it that way, but that is a more advanced technique. The first link shows how, but I wouldn’t worry about it for now - walk before you can fly.

It’s weird though how the challenge gave the advanced technique as an example when the challenge needs you to apply the simple technique. I feel like they should change that. Especially since submitting the advanced technique as the solution will cause a crash. Or maybe it only happens to me :frowning:

Oh, I see that they do talk about compositional components. Go figure.