Skip to content
Advertisement

Disabled When Lacking Input in Field in React

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?

CLICK HERE

   <div className="App">
      <InputCode
        length={6}
        label="Code Label"
        loading={loading}
        onComplete={(code) => {
          setCodes(code);
          setLoading(true);
          setTimeout(() => setLoading(false), 10000);
        }}
      />
      <br />
      <button disabled={codes?.length < 6 || !codes}>Submit</button>
    </div>

Answer

To do that, you would instead get disabled state from your child:

  • Adding a new state to your parent component:
const [disabled, setDisabled] = useState(true);
  • Pass it down to your child component:
<InputCode
        length={6}
        label="Code Label"
        loading={loading}
        onComplete={(code) => {
          setLoading(true);
          setTimeout(() => setLoading(false), 10000);
        }}
        setDisabled={setDisabled}
/>
  • Set the status of your button base on that state:
<button disabled={disabled}>Submit</button>
  • Import setDisabled ot your child component and add useEffect like this:
  useEffect(() => {
    if (code.some((num) => num === "")) {
      setDisabled(true);
    } else {
      setDisabled(false);
    }
  }, [code, setDisabled]);

Working Example

Advertisement