After this lesson, you will be able to:
…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?
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.
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?
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:
import React, { Component } from 'react';
import './App.css';
// Load in Comment component.
import Comment from './Comment.js';
<p>{this.props.comments[0]}</p>
What We Did
<Comment body={this.props.comments[0]} />
passed just the first object in the comments
array.
What Else Can We Do?
class Post extends Component {
render() {
let allComments = [
<Comment body={this.props.comments[0]} />,
<Comment body={this.props.comments[1]} />,
<Comment body={this.props.comments[2]} />
]
/// Rest of content...
}
}
We could then call this object inside our return
JSX with {allComments}
, which would then call all three of those <Comment />
statements:
<div>
<h1>{this.props.title}</h1>
<p>by {this.props.author}</p>
<div>
<p>{this.props.body}</p>
</div>
<h3>Comments:</h3>
{allComments}
</div>