I have set of inputs that needs to be filled out completely. I should disable the submit button when its not complete. Its working fine until I decided to erase and fill it out again. It never disables. What would be the proper and correct way to do this? Is there a better way to do this?
JavaScript
x
15
15
1
<div className="App">
2
<InputCode
3
length={6}
4
label="Code Label"
5
loading={loading}
6
onComplete={(code) => {
7
setCodes(code);
8
setLoading(true);
9
setTimeout(() => setLoading(false), 10000);
10
}}
11
/>
12
<br />
13
<button disabled={codes?.length < 6 || !codes}>Submit</button>
14
</div>
15
Advertisement
Answer
To do that, you would instead get disabled state from your child:
- Adding a new state to your parent component:
JavaScript
1
2
1
const [disabled, setDisabled] = useState(true);
2
- Pass it down to your child component:
JavaScript
1
11
11
1
<InputCode
2
length={6}
3
label="Code Label"
4
loading={loading}
5
onComplete={(code) => {
6
setLoading(true);
7
setTimeout(() => setLoading(false), 10000);
8
}}
9
setDisabled={setDisabled}
10
/>
11
- Set the status of your button base on that state:
JavaScript
1
2
1
<button disabled={disabled}>Submit</button>
2
- Import setDisabled ot your child component and add useEffect like this:
JavaScript
1
8
1
useEffect(() => {
2
if (code.some((num) => num === "")) {
3
setDisabled(true);
4
} else {
5
setDisabled(false);
6
}
7
}, [code, setDisabled]);
8