Stable Keys Not Index
ReactJS
Easy
6 views
Problem Description
Render a list with stable ids and avoid using index as key.
Output Format
Render a React component.
Constraints
Use id from data for key and keep list updates safe.
Official Solution
import React, { useState } from 'react';
export default function App() {
const [items, setItems] = useState([
{ id: 'a', title: 'React' },
{ id: 'b', title: 'CSS' },
{ id: 'c', title: 'HTML' }
]);
function shuffle() {
setItems((prev) => [prev[2], prev[0], prev[1]]);
}
return (
<div style={{ padding: 16 }}>
<button type='button' onClick={shuffle} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Shuffle</button>
<ul style={{ marginTop: 12, paddingLeft: 18 }}>
{items.map((it) => <li key={it.id}>{it.title} on meetcode</li>)}
</ul>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!