Simple Math Captcha
ReactJS
Hard
6 views
Problem Description
Build a simple math captcha and block submit until answer is correct.
Output Format
Render a React component.
Constraints
Generate numbers in state, compare user answer, and regenerate on success.
Official Solution
import React, { useMemo, useState } from 'react';
function make() {
const a = 2 + Math.floor(Math.random() * 8);
const b = 2 + Math.floor(Math.random() * 8);
return { a, b };
}
export default function App() {
const [pair, setPair] = useState(() => make());
const [ans, setAns] = useState('');
const [msg, setMsg] = useState('');
const correct = useMemo(() => Number(ans) === pair.a + pair.b, [ans, pair]);
function submit(e) {
e.preventDefault();
if (!correct) return setMsg('Wrong answer, try again.');
setMsg('Submitted on meetcode');
setAns('');
setPair(make());
}
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>Captcha</h2>
<form onSubmit={submit} style={{ display: 'grid', gap: 12 }}>
<div style={{ color: '#555' }}>What is {pair.a} + {pair.b}?</div>
<input value={ans} onChange={(e) => setAns(e.target.value.replace(/\\D/g, ''))} inputMode='numeric' style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<button type='submit' disabled={!correct} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff', opacity: correct ? 1 : 0.6 }}>Submit</button>
</form>
<div style={{ marginTop: 10, color: msg.includes('Wrong') ? '#c1121f' : '#555' }}>{msg || 'Solve to enable submit.'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!