ReactJS Program to useId For Form Labels with Explanation
ReactJS
Medium
Hooks & Effects
24 views
1 min read
92 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around useid, form, label. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Build a small form that uses useId to link label and input.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use useId so ids stay stable even with multiple component instances.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
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>
);
}
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).
Solution Guide
Problem
Build a small form that uses useId to link label and input.
Input / Output
Output
Render a React component.
Constraints
Use useId so ids stay stable even with multiple component instances.
Details
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).
Difficulty
Medium
ReactJS
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!