Is this how you nest React components?

Is this how you nest React components?
0.0 0

#1

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.


#2

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.


#3

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


#4

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.


#5

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:


React Challenge: "Create a Component with Composition" freezes every time the challenge page loads
#6

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