MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Inline Edit List Item with Explanation

ReactJS Hard State Management 21 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around list, edit, item. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Render a list of titles and let user edit one item at a time.

Input Format

No input.

Output Format

Render a React component.

Constraints

Keep editing id and draft text in state and update the list on save.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useMemo, useState } from 'react'; export default function App() { const [items, setItems] = useState([ { id: '1', title: 'React hooks' }, { id: '2', title: 'State basics' }, { id: '3', title: 'Forms validation' } ]); const [editingId, setEditingId] = useState(''); const [draft, setDraft] = useState(''); const editing = useMemo(() => items.find((x) => x.id === editingId), [items, editingId]); function startEdit(id) { const it = items.find((x) => x.id === id); setEditingId(id); setDraft(it.title); } function save() { const t = draft.trim(); if (!t) return; setItems((prev) => prev.map((x) => x.id === editingId ? { ...x, title: t } : x)); setEditingId(''); setDraft(''); } function cancel() { setEditingId(''); setDraft(''); } return ( <div style={{ padding: 16, width: 520 }}> <h2 style={{ marginTop: 0 }}>meetcode saved list</h2> <ul style={{ paddingLeft: 18 }}> {items.map((x) => ( <li key={x.id} style={{ marginBottom: 8 }}> {editingId === x.id ? ( <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}> <input value={draft} onChange={(e) => setDraft(e.target.value)} style={{ padding: '8px 10px', borderRadius: 12, border: '1px solid #bbb', width: 260 }} /> <button type='button' onClick={save} style={{ padding: '8px 12px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Save</button> <button type='button' onClick={cancel} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Cancel</button> </span> ) : ( <span style={{ display: 'inline-flex', gap: 10, alignItems: 'center' }}> <span>{x.title}</span> <button type='button' onClick={() => startEdit(x.id)} style={{ padding: '6px 10px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Edit</button> </span> )} </li> ))} </ul> {editing ? <div style={{ marginTop: 10, color: '#555' }}>Editing: {editing.title}</div> : null} </div> ); }

Output Example

No sample I/O is provided for this question.

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next