How to conditionally disable an input field in React

#react

Last updated on Jun 14, 2021 by Suraj Sharma



In this tutorial, you will learn to conditionally disable an input text field in React using useState hook

Input fields are disabled using the disabled attribute, which accepts truthy value to disable the Input fields.


<input disabled="true" />


Create a local state


To disable an input field inside a <Form /> function component, we will use isDisabled local state and it’s setter method setIsDisabled, defined using the useState() hook.


import React from 'react';

const Form = ()=>{ 

  const [isDisabled, setIsDisabled] = useState(false);

  return (
    <form>
      <input type="text" disabled={isDisabled} />
    </form>
  );
}

export default Form;


Disable Input field on button click


Use the button’s onClick event handler function handleClick to toggle the isDisable state value

Finally, pass theisDisabled state to the disabled attribute of the <input /> element


import React from 'react';

const Form = ()=>{ 

  const [isDisabled, setIsDisabled] = useState(false);

  const handleClick = () => {
    setIsDisabled(!isDisabled)
  };

  return (
    <form>
      <input type="text" disabled={isDisabled} />
      <button type="button" onClick={handleClick}>
        Toggle
      </button>
    </form>
  );
}


Disable Input field on componentDidMount


To disable the Input field after the first render or on componentDidMount event we can simply initialize the isDisabled to true, by passing the true value to the useState() hook


const [isDisabled, setIsDisabled] = useState(true);


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.