Challenges

Add Comments Support

View Comments in the UI

Now we have an API to add comments. Let's render these comments inside the UI.

To do that, create a file called components/Comments.js inside your app and add the following code:

import Markdown from 'markdown-to-jsx'
import ms from 'ms'

export default function Comments({slug}) {
    const comments = []

    if (!comments) {
        return (
            <div className="comments">
                <div className="comments-info">
                    loading...
                </div>
            </div>
        )
    }

    return (
        <div>
            {comments && comments.length > 0 ? (
                <div className="comments">
                    {comments.map(c => (
                        <div key={c.id} className={c.clientOnly? 'comment client-only' : 'comment'}>
                            <div className="comment-content">
                                <Markdown>{c.content || ''}</Markdown>
                            </div>
                            <div className="comment-author">
                                <img src={c.avatar} title={c.name}/>
                                <div>{c.name} ({ms(Date.now() - c.createdAt)} ago)</div>
                            </div>
                        </div>
                    ))}
                </div>
            ) : (
                <div className="comments">
                    <div className="comments-info">
                        No comments so far.
                    </div>
                </div>
            )}
        </div>
    )
}

After that, import the above component on the top of the pages/post/[slug].js file:

import Comments from '../../components/Comments'

Then add the following code to render the UI right after we render the blog post content.

<b>Comments</b>
<Comments slug={post.slug}/>

(Here's the final version of the file after all these changes.)

Now, let's verify this functionality:

  • Open a blog post in your app
  • Check the content after "Comments"
Q: What's the outcome?
authenticating...

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: