Nested Components


Learning Objectives:

After this lesson, you will be able to:

  • Diagram nested components.
  • Render components within another component.
  • Pass props to a nested component.

In Your Blog…

…a section of your App.js render() function currently looks like this:

Discussion: While you can certainly display more comments with <p>{this.props.comments[1]}</p>, <p>{this.props.comments[2]}</p>, etc., do you think this is the best way?


In Your Blog…

Next, we’ll put comments inside an individual Post component. To do this, we can reference a comment using <Comment /> inside of Post’s render() method.

  • Starting from the blog post code, let’s create a new file for a Comment component, src/Comment.js:
import React, {Component} from 'react';

class Comment extends Component {
  render () {
    return (
      <div>
        <p>{this.props.body}</p>
      </div>
    )
  }
}

export default Comment

Discussion: What have we done?


In Your Blog…

Now, in src/App.js, we need to import our Comment component so it’s available to the Post component class. * Change the top of App.js to include the new class:


In Your Blog…

<p>{this.props.comments[0]}</p>


In Your Blog…


What Just Happened?!


Nested Components

nested components chart
nested components chart

Recap

What We Did

<Comment body={this.props.comments[0]} /> passed just the first object in the comments array.

What Else Can We Do?

nested components meme
nested components meme

Code-Along


Code-Along

We could then call this object inside our return JSX with {allComments}, which would then call all three of those <Comment /> statements:


Code-Along