Form Reset To Defaults
ReactJS
Medium
6 views
Problem Description
Build a form with Reset button that restores default values.
Output Format
Render a React component.
Constraints
Keep defaults in an object and reset state to it.
Official Solution
import React, { useState } from 'react';
const defaults = { name: 'Meetcode Learner', city: 'Delhi' };
export default function App() {
const [form, setForm] = useState(defaults);
function change(key, value) {
setForm((prev) => ({ ...prev, [key]: value }));
}
function reset() {
setForm(defaults);
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>Reset example</h2>
<div style={{ display: 'grid', gap: 10 }}>
<input value={form.name} onChange={(e) => change('name', e.target.value)} style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<input value={form.city} onChange={(e) => change('city', e.target.value)} style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
</div>
<div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
<button type='button' onClick={reset} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Reset</button>
<button type='button' onClick={() => alert('Saved on meetcode')} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Save</button>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!