I am trying to disable a button after it is clicked, but it is not holding its disabled tag. Another weird thing is that if I click the button twice it will disable. Code below
const [loading, setLoading] = useState('Submit');
...
<form onSubmit={(event) => {
event.preventDefault();
submitBet(units, line, team, gameID);
}}>
...
<button type='submit' className='submit-betslip' id='submit-button-id'>{loading}.</button>
</form>
The loading variable is a useState. The onSubmit function:
const submitBet = async (units, line, team, id) => {
if (Number(units) === 0 && Number(line) === 0) {
console.log('Empty input');
return
}
try {
document.getElementById('submit-button-id').disabled = true;
}
...
}
Not sure if it matters but the form is within a React function. Any thoughts?
Here is a simple example to what you want to do and it's working perfectly.
import React from "react";
import "./styles.css";
export default function App() {
const [loading, setLoading] = React.useState("Submit");
const handleSubmit = (e) => {
e.preventDefault();
setLoading("Submitting..");
setTimeout(() => {
alert("submitted Successfully");
setLoading("Submit");
}, 3000);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<form onSubmit={handleSubmit}>
<input id="f1" name="f1" />
<button type="submit" disabled={loading !== "Submit"}>
{loading}.
</button>
</form>
</div>
);
}
Simply link the disable prop to the loading state.
If that is not what you want to do, just share the component with us, and I would love to help.