Build a React commenting system with Firebase that supports infinite nested replies. Store comments in a flat Firestore collection with parentId and path strings, reconstructing the tree on the client recursively.
Assistant
Outlining React nested comments with Firestore
I detailed a Firestore schema using a flat comments collection with parentId and a path string for each comment, plus React code snippets that subscribe to comments, reconstruct the nested tree recursively on the client via a map-based algorithm, and render infinite nested replies with reply forms and Firestore writes creating paths based on generated doc IDs.
A simple way to get “infinite” nesting without paying the cost of sub‑collections is to treat every comment as a row in a single collection and give each row enough metadata to reconstruct its position in the tree.
A minimal document shape that works well for this looks like:
js
// /comments/{id}
{
id: "auto‑id", // Firestore document id
content: "Hello world",
authorUid: "…",
parentId: null | "…", // null for top–level, otherwise the parent's id
path: "rootId/foo/bar", // all ancestor ids + self, slash‑separated
createdAt: Timestamp
}
The path is built on write by appending the new id to the parent’s path (or just the new id if it’s a root). On the client you can then fetch comments from /comments and reassemble the hierarchy by walking parentIds.
Below is a complete but compact example in React using the modular Firebase SDK:
jsx
// firebase.js
import { initializeApp } from 'firebase/app';
import {
getFirestore, collection, doc, onSnapshot,
query, orderBy, setDoc, serverTimestamp
} from 'firebase/firestore';
const firebaseConfig = { /* your config */ };
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const commentsCol = collection(db, 'comments');
export async function addComment({ content, parent }) {
// create a docRef so we know the id up front
const ref = doc(commentsCol);
const parentPath = parent ? parent.path : '';
const path = parentPath ? `${parentPath}/${ref.id}` : ref.id;
await setDoc(ref, {
id: ref.id,
content,
parentId: parent ? parent.id : null,
path,
createdAt: serverTimestamp()
});
}
A helper to turn a flat array into a tree:
js
function buildTree(comments) {
const map = new Map();
const roots = [];
comments.forEach(c => map.set(c.id, { ...c, children: [] }));
map.forEach(node => {
if (node.parentId) {
const parent = map.get(node.parentId);
if (parent) {
parent.children.push(node);
} else {
// orphaned node, treat as root if you want
roots.push(node);
}
} else {
roots.push(node);
}
});
return roots;
}
React components to subscribe, render and reply recursively:
The path field is written for each comment to make it trivial to see the ancestry; if you need to query a specific thread you can include the ancestor id in the path and filter client‑side. Firestore doesn’t have “startsWith” queries, so you still fetch the relevant slice (by e.g. createdAt) and prune by path prefix on the client.
orderBy('createdAt') is used above for deterministic rendering; you could order by path as well if you want parent‑before‑child.
Because rendering is recursive (<Comment> calls itself for children), the depth is limited only by the data.
With this pattern all comments live in one collection, you never need to create nested subcollections, and you can render an arbitrarily deep reply tree by building it in memory.