Accessible Error Messages
ReactJS
Medium
5 views
Problem Description
Build a field that links error text using aria-describedby.
Output Format
Render a React component.
Constraints
Give error element an id and attach it to input when error exists.
Official Solution
import React, { useId, useState } from 'react';
export default function App() {
const [value, setValue] = useState('');
const [touched, setTouched] = useState(false);
const errId = useId();
const error = touched && value.trim().length < 3 ? 'Enter at least 3 characters' : '';
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode accessibility</h2>
<label style={{ fontWeight: 700 }}>Display name</label>
<input
value={value}
onChange={(e) => setValue(e.target.value)}
onBlur={() => setTouched(true)}
aria-invalid={!!error}
aria-describedby={error ? errId : undefined}
style={{ marginTop: 6, width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid ' + (error ? '#c1121f' : '#bbb') }}
/>
{error ? <div id={errId} style={{ marginTop: 8, color: '#c1121f' }}>{error}</div> : <div style={{ marginTop: 8, color: '#555' }}>Looks good.</div>}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!