ReactJS Program to Disable Button During Work with Explanation
ReactJS
Medium
State Management
26 views
1 min read
88 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around button, react, disable. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a button that becomes disabled while a fake async task is running.
Input Format
No input.
Output Format
Render a React component.
Constraints
Use state to block repeated clicks.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react';
function wait(ms) {
return new Promise((r) => setTimeout(r, ms));
}
export default function App() {
const [saving, setSaving] = useState(false);
const [msg, setMsg] = useState('');
async function handleSave() {
setSaving(true);
setMsg('Saving...');
await wait(700);
setMsg('Saved on meetcode.');
setSaving(false);
}
return (
<div style={{ padding: 16 }}>
<button type='button' disabled={saving} onClick={handleSave} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff', opacity: saving ? 0.7 : 1 }}>
{saving ? 'Saving' : 'Save'}
</button>
<div style={{ marginTop: 10, color: '#555' }}>{msg}</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 button that becomes disabled while a fake async task is running.
Input / Output
Output
Render a React component.
Constraints
Use state to block repeated clicks.
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 wait(ms) {
return new Promise((r) => setTimeout(r, ms));
}
export default function App() {
const [saving, setSaving] = useState(false);
const [msg, setMsg] = useState('');
async function handleSave() {
setSaving(true);
setMsg('Saving...');
await wait(700);
setMsg('Saved on meetcode.');
setSaving(false);
}
return (
<div style={{ padding: 16 }}>
<button type='button' disabled={saving} onClick={handleSave} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff', opacity: saving ? 0.7 : 1 }}>
{saving ? 'Saving' : 'Save'}
</button>
<div style={{ marginTop: 10, color: '#555' }}>{msg}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!