useId For Form Labels
ReactJS
Medium
7 views
Problem Description
Build a small form that uses useId to link label and input.
Output Format
Render a React component.
Constraints
Use useId so ids stay stable even with multiple component instances.
Official Solution
import React, { useId, useState } from 'react';
function Field({ label, value, onChange }) {
const id = useId();
return (
<div style={{ display: 'grid', gap: 6 }}>
<label htmlFor={id} style={{ fontWeight: 700 }}>{label}</label>
<input id={id} value={value} onChange={(e) => onChange(e.target.value)} style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
</div>
);
}
export default function App() {
const [name, setName] = useState('');
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode form</h2>
<Field label='Name' value={name} onChange={setName} />
<div style={{ marginTop: 10, color: '#555' }}>Hello {name || '...'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!