Lists in React — React Technical Interview Questions & Answers
Lists in React
Lists in React
- A list in React is an array turned into elements with map. items.map(it => <li key={it.id}>{it.name}</li>). You almost never write a for-loop inside JSX — for is a statement, JSX wants an expression. You can still use a normal for above the return: build an array of elements, then {rows} in JSX.
- Each item needs a key (see the Keys topic). Extract <Row /> when the item UI grows past a line or two. Don’t use map to mutate the original array — map returns a new array, which is what we want. filter then map is the usual pair: show only in-stock products, then draw cards.
- Let’s take a tiny shop on the board. const items = [{ id: 'a1', name: 'Pen' }, { id: 'a2', name: 'Ink' }]; return <ul>{items.map(it => <li key={it.id}>{it.name}</li>)}</ul>; Screen: Pen, Ink. Delete Pen from the array, Ink stays Ink — because the key was a2, not index 1 that became 0.
- Empty list: don’t render a blank ul with no message. {items.length === 0 ? <p>No items</p> : <ul>…</ul>}. Loading: show a spinner until the array arrives. Those two branches are part of ‘lists’ in real apps, not extra topics.
- Trap: forEach inside JSX (returns undefined, nothing draws). Trap: missing key warning you ignore. Trap: using the object itself as key. Trap: mapping a huge list without virtualisation in a later performance round — mention windowing only if they ask.
- Lists in React — on screen: Pen, Ink. Each li has a stable id key.
items[]
│ .map
▼
<li key={id}>Technical Interview Tip: map + key + stable id.
Code Examples for Lists in React
Example
// Lists
const items = [
{ id: "a1", name: "Pen" },
{ id: "a2", name: "Ink" },
];
export default function Shop() {
return (
<ul>
{items.map((it) => (
<li key={it.id}>{it.name}</li>
))}
</ul>
);
}
Lists in React — on screen: Pen, Ink. Each li has a stable id key.
How to Explain Lists in React to an Interviewer
Explain Lists as if you are teaching a junior — definition, then one tiny UI.
A React list is an array turned into elements with map. Each child needs a stable key. map inside JSX (expression). for/forEach belong above return, not inside the braces.
What does the example show on screen (or print), and what does that prove?
Lists in React — on screen: Pen, Ink
What mistake do freshers make with Lists?
forEach in JSX (draws nothing). Ignoring the key warning. Index keys on a list that reorders.