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

Files touched

--- 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>
+  );
+}

Review this PR

React practice