import React, {
useState
} from "react";
export default function DropDown() {
const [mail, useEmail] = useState("");
const [disabled, useDisabled] = useState(false)
const handleChange = (e) => {
useEmail(e.target.value)
}
if (mail.includes('s@gmail.com')) {
React.useEffect(() => {
setInterval(() => {
useDisabled(true);
}, 2000);
})
} else {
useDisabled(false)
}
return (
<>
<input
value={ mail }
onChange={ handleChange }
maxLength="20"
/>
<button
disabled={ mail.length < 1 }
> Submit </button>
</>
);
}
but at the time it throws error like "Too many re-renders. React limits the number of renders to prevent an infinite loop." how to resolve that error?
>Solution :
TL.DR:
import React, { useState } from "react";
export default function DropDown() {
const [mail, setEmail] = useState("");
const handleChange = (e) => {
setEmail(e.target.value);
};
return (
<>
<input value={mail} onChange={handleChange} maxLength={20} />
<button disabled={mail.includes("s@gmail.com") || mail.length < 1}> Submit </button>
</>
);
}
Let’s break it down:
- Hooks (
useState,useEffect, etc) cannot be conditionally rendered, so you cannot write them insideif elsestatements. const [mail, setMail] = useState(""). The second attribute should besetSomething, notuseSomething. TheuseSomethingshould be reserved to the declarations of new hooks. ThesetMailreturned by theuseStateis not a hook, but a normal function (theuseStateitself is the hook).setState(orsetDisabled, in your example) should never be used directly inside the render of a component. AsetStatecauses the component to re-render so, if when re-rendering asetStateis encountered, it will trigger another re-render, that will trigger anothersetState, and so on (leading to the ""Too many re-renders." you had). Generally speaking,setStateshould only be used on event handlers (such asonClick,onKeyDown,onSomethingElseHapped, etc)
There are a few more minor issues with your code. I encourage you to go through the basics of react one more time.