Error Summary On Submit
ReactJS
Hard
5 views
Problem Description
On submit, show a small error summary list at top.
Output Format
Render a React component.
Constraints
Validate required fields and render a summary block.
Official Solution
import React, { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [errors, setErrors] = useState([]);
function submit(e) {
e.preventDefault();
const next = [];
if (!name.trim()) next.push('Name is required');
if (!email.trim()) next.push('Email is required');
setErrors(next);
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode profile</h2>
{errors.length ? (
<div style={{ border: '1px solid #ffc2c7', background: '#ffe8ea', padding: 12, borderRadius: 14 }}>
<strong>Please fix:</strong>
<ul style={{ margin: '8px 0 0 0', paddingLeft: 18 }}>
{errors.map((e) => <li key={e}>{e}</li>)}
</ul>
</div>
) : null}
<form onSubmit={submit} style={{ marginTop: 12, display: 'grid', gap: 10 }}>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder='Name' style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<input value={email} onChange={(e) => setEmail(e.target.value)} placeholder='Email' style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<button type='submit' style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>Save</button>
</form>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!