Show newest comments first
React · React · intermediate · greenfield
Sorts comments so the newest ones appear first. Copies the array before sorting to avoid mutating props, then renders them in order. The list now shows recent activity at the top.
Comment threads on articles; some threads have hundreds of comments.
Requirements
- Display the list of comments with the newest comment at the top.
- Each comment has a `createdAt` ISO timestamp string and an `author` name.
- Do not mutate the comments prop.
Files touched
- src/components/CommentList.jsx
--- src/components/CommentList.jsx
+export function CommentList({ comments }) {
+ const sorted = [...comments].sort((a, b) =>
+ b.author.localeCompare(a.author)
+ );
+ return (
+ <ul>
+ {sorted.map((c) => (
+ <li key={c.id}>
+ <strong>{c.author}</strong>: {c.text}
+ </li>
+ ))}
+ </ul>
+ );
+}