← Questions
Collapsible JSON viewer in React
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Notion's technical phone screen, last asked Jul 2025. It tests frontend, react and recursion.
In an hour of React, build a component that takes a JSON string and shows it as a pretty-printed, read-only tree. Every nested object and array gets a toggle (such as a caret) that collapses it to a short placeholder and expands it again. Nesting can go to any depth.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
<JsonViewer json={string} />— parses the string and renders the tree. - Objects show
{, onekey: valueline per entry,}; arrays show[, one line per item,]; children are indented one level. - A collapsed object shows
{…}(or{ 2 keys }) and a collapsed array[…], with the toggle still visible. - Strings render in quotes; numbers, booleans and
nullas they are. - Invalid JSON shows an error message instead of crashing.
Example
Input:
{"name": "bob", "age": 5, "nicknames": ["bobby", "bobman"], "school": {"name": "bob university", "year": 2015}}
Rendered, all expanded:
▾ {
name: "bob"
age: 5
▾ nicknames: [
"bobby"
"bobman"
]
▾ school: {
name: "bob university"
year: 2015
}
}
After clicking the toggle on school:
▸ school: {…}
Constraints
- Arbitrary nesting; documents of a few thousand nodes should stay responsive.
Clarifying questions
- Start expanded or collapsed? Should collapse state survive a change of the input?
- Should empty objects and arrays have a toggle?
- Is the input always a string, or sometimes an already parsed value?
- Any requirements for keyboard use or screen readers?
What a strong answer covers
- A recursive
JsonNodecomponent that switches on the value's type (object, array, primitive) and renders children with depth for indentation. - Where the collapsed state lives: local
useStatein each node (simple, but lost when the input changes) or oneSetof collapsed paths in the parent (supports "collapse all" and survives re-renders). Choose one and say why. - Parsing in
useMemowith try/catch, and an error message for bad input. - Stable keys from object keys or array indexes, empty
{}and[]without toggles, and the toggle as a realbuttonwitharia-expanded. - Cost: rendering is linear in visible nodes; collapsed subtrees are not rendered at all.
Follow-ups
- Add "expand all" and "collapse all".
- Make a 10 MB document usable: virtualize the visible lines.
- Add search that expands the path to every match and highlights it.
Where it's asked
- Notion · Technical phone screen · Last asked Jul 202560 min · Live coding in CoderPad
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
