Number Input With Limits
ReactJS
Medium
7 views
Problem Description
Create a number input with min/max and show an error message.
Output Format
Render a React component.
Constraints
Validate value and show error in UI.
Official Solution
import React, { useMemo, useState } from 'react';
export default function App() {
const [value, setValue] = useState('');
const error = useMemo(() => {
if (!value) return '';
const n = Number(value);
if (Number.isNaN(n)) return 'Enter a number';
if (n < 1) return 'Min is 1';
if (n > 50) return 'Max is 50';
return '';
}, [value]);
return (
<div style={{ padding: 16, width: 420 }}>
<h2 style={{ marginTop: 0 }}>meetcode streak</h2>
<label>
Target days (1-50)
<div>
<input inputMode='numeric' value={value} onChange={(e) => setValue(e.target.value)} style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid ' + (error ? '#c1121f' : '#bbb') }} />
</div>
</label>
{error ? <div style={{ marginTop: 10, color: '#c1121f' }}>{error}</div> : null}
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!