Implementing recursive React form with topological visibility logic
I've designed a React form generator that flattens the recursive schema, builds a dependency graph including parent-child and showIf conditions, and uses topological sorting to evaluate field visibility in the correct order. The form updates values and visibility together in a reducer to ensure all dependent fields' visibility states update correctly in a single render pass.
Below is a self‑contained example of a recursive form generator that:
- Takes a nested JSON schema.
- Each node can declare a
showIf condition (e.g. “show B if A > 10”).
- Builds a dependency graph from those conditions and parent/child relationships.
- Uses a topological sort of that graph to determine the evaluation order.
- Evaluates visibility in one pass whenever a value changes.
Because we evaluate in a deterministic topological order, updates propagate through all dependents in a single render.
import React, {useMemo, useReducer} from "react";
// Example recursive schema
const schema = {
id: "root",
type: "group",
label: "Root",
children: [
{ id: "fieldA", label: "Field A (number)", type: "number" },
{ id: "fieldB", label: "Field B (text, shown if A > 10)", type: "text", showIf: { field: "fieldA", op: ">", value: 10 } },
{
id: "group1",
label: "Group 1 (shown if B is not empty)",
type: "group",
showIf: { field: "fieldB", op: "!=", value: "" },
children: [
{ id: "fieldC", label: "Field C (number, shown if A < 20)", type: "number", showIf: { field: "fieldA", op: "<", value: 20 } },
{ id: "fieldD", label: "Field D (text, always visible if parent visible)", type: "text" }
]
}
]
};
// Helper to evaluate a simple condition
function evaluateCondition(cond, values) {
const left = values[cond.field];
const right = cond.value;
switch (cond.op) {
case ">": return Number(left) > right;
case "<": return Number(left) < right;
case "==": return left == right;
case "!=": return left != right;
case ">=": return Number(left) >= right;
case "<=": return Number(left) <= right;
default: return false;
}
}
// Flatten the recursive schema into a node map and build dependency graph
function collectNodesAndGraph(tree, parentId = null, nodes = {}) {
const current = {
id: tree.id,
type: tree.type || "field",
label: tree.label,
showIf: tree.showIf,
parentId,
children: []
};
nodes[current.id] = current;
if (Array.isArray(tree.children)) {
tree.children.forEach(child => {
current.children.push(child.id);
collectNodesAndGraph(child, current.id, nodes);
});
}
return nodes;
}
// Build adjacency list graph: edge from dependency -> dependent
function buildDependencyGraph(nodes) {
const graph = new Map();
Object.keys(nodes).forEach(id => graph.set(id, new Set()));
Object.values(nodes).forEach(node => {
// Parent -> child (visibility depends on parent)
node.children.forEach(childId => {
graph.get(node.id).add(childId);
});
// showIf dependency: referenced field -> this node
if (node.showIf && node.showIf.field) {
if (!graph.has(node.showIf.field)) {
graph.set(node.showIf.field, new Set());
}
graph.get(node.showIf.field).add(node.id);
}
});
return graph;
}
// Topological sort using Kahn's algorithm
function topoSort(graph) {
const indegree = new Map();
// initialize indegrees to 0
graph.forEach((_, node) => indegree.set(node, 0));
graph.forEach((neighbors) => {
neighbors.forEach(n => indegree.set(n, (indegree.get(n) || 0) + 1));
});
const queue = [];
indegree.forEach((deg, node) => { if (deg === 0) queue.push(node); });
const order = [];
while (queue.length > 0) {
const node = queue.shift();
order.push(node);
graph.get(node).forEach(n => {
indegree.set(n, indegree.get(n) - 1);
if (indegree.get(n) === 0) queue.push(n);
});
}
return order;
}
// Compute visibility map given current values
function computeVisibility(nodes, topoOrder, values) {
const visible = {};
topoOrder.forEach(id => {
const node = nodes[id];
// Default to visible unless a condition fails
let isVisible = true;
// If parent is hidden, child is hidden
if (node.parentId && visible[node.parentId] === false) {
isVisible = false;
}
// Apply showIf condition
if (node.showIf) {
isVisible = isVisible && evaluateCondition(node.showIf, values);
}
visible[id] = isVisible;
});
return visible;
}
// Recursive renderer
function RenderNode({nodeId, nodes, visible, values, dispatch}) {
const node = nodes[nodeId];
if (!visible[nodeId]) {
return null;
}
if (node.type === "group") {
return (
<fieldset style={{ border: "1px solid #ccc", padding: "0.5rem", margin: "0.5rem 0" }}>
<legend>{node.label}</legend>
{node.children.map(childId => (
<RenderNode
key={childId}
nodeId={childId}
nodes={nodes}
visible={visible}
values={values}
dispatch={dispatch}
/>
))}
</fieldset>
);
}
// default field renderer
return (
<div style={{ marginBottom: "0.5rem" }}>
<label>
{node.label}:{" "}
<input
type={node.type === "number" ? "number" : "text"}
value={values[node.id] ?? ""}
onChange={e =>
dispatch({ type: "change", id: node.id, value: node.type === "number" ? e.target.valueAsNumber : e.target.value })
}
/>
</label>
</div>
);
}
function FormGenerator({ schema }) {
// Flatten schema and precompute graph/topo order once
const { nodes, topoOrder } = useMemo(() => {
const nodes = collectNodesAndGraph(schema);
const graph = buildDependencyGraph(nodes);
const topoOrder = topoSort(graph);
return { nodes, topoOrder };
}, [schema]);
// Initialize all values to empty
const initialValues = useMemo(() => {
const vals = {};
Object.keys(nodes).forEach(id => { vals[id] = ""; });
return vals;
}, [nodes]);
// Reducer to update values and recompute visibility in one pass
function reducer(state, action) {
switch (action.type) {
case "change": {
const newValues = { ...state.values, [action.id]: action.value };
const newVisible = computeVisibility(nodes, topoOrder, newValues);
return { values: newValues, visible: newVisible };
}
default:
return state;
}
}
const [state, dispatch] = useReducer(reducer, null, () => {
const vis = computeVisibility(nodes, topoOrder, initialValues);
return { values: initialValues, visible: vis };
});
return (
<form>
<RenderNode
nodeId={schema.id}
nodes={nodes}
visible={state.visible}
values={state.values}
dispatch={dispatch}
/>
<pre>Values: {JSON.stringify(state.values, null, 2)}</pre>
<pre>Visible: {JSON.stringify(state.visible, null, 2)}</pre>
</form>
);
}
// Usage
export default function App() {
return (
<div style={{ padding: "1rem" }}>
<h1>Topologically Evaluated Dynamic Form</h1>
<FormGenerator schema={schema} />
</div>
);
}
How it works:
- The schema is traversed once to produce a flat
nodes map.
- The dependency graph has edges from each dependency to the nodes that depend on it:
- Parent → child (children are hidden if parent is hidden).
showIf.field → the node with that condition.
- A topological sort (
topoOrder) of the graph gives the order in which dependencies are guaranteed to be processed before dependents.
- On any change, the reducer recomputes both
values and visible by iterating topoOrder and applying parent visibility and showIf conditions. Because dependents are evaluated after their dependencies, updates propagate in one pass.