ReactJS Program to Compound Input With Label with Explanation
ReactJS
Medium
Forms & Validation
19 views
1 min read
87 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around label, component, render. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a Field component that renders label + input and accepts id/name props.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use htmlFor and id properly.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react';
function Field({ label, id, value, onChange, type = 'text' }) {
return (
<div style={{ display: 'grid', gap: 6 }}>
<label htmlFor={id} style={{ fontWeight: 600 }}>{label}</label>
<input id={id} type={type} value={value} onChange={(e) => onChange(e.target.value)} style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
</div>
);
}
export default function App() {
const [email, setEmail] = useState('');
return (
<div style={{ padding: 16, width: 420 }}>
<Field label='Email' id='email' type='email' value={email} onChange={setEmail} />
<div style={{ marginTop: 10, color: '#555' }}>Typing: {email}</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
Create a Field component that renders label + input and accepts id/name props.
Input / Output
Output
Render a React component.
Constraints
Use htmlFor and id properly.
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, { useState } from 'react';
function Field({ label, id, value, onChange, type = 'text' }) {
return (
<div style={{ display: 'grid', gap: 6 }}>
<label htmlFor={id} style={{ fontWeight: 600 }}>{label}</label>
<input id={id} type={type} value={value} onChange={(e) => onChange(e.target.value)} style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
</div>
);
}
export default function App() {
const [email, setEmail] = useState('');
return (
<div style={{ padding: 16, width: 420 }}>
<Field label='Email' id='email' type='email' value={email} onChange={setEmail} />
<div style={{ marginTop: 10, color: '#555' }}>Typing: {email}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!