Search code examples
javascriptreactjstailwind-in-jstailwind-css

How to disable input filed using tailwind css and react conditionally?


Hello Dev Community i am here with another issue can need your help.

i want to disable input field based on the Boolean state if the state is true then the input filed should be disable else it can be editable.

i have state variable isTrue which can be eithe true or false and here is the code

export function InputFiled(props) {
  return (
    <>
      <input
        className="py-2 pl-3 rounded-[14px] border-[1.3px] border-red-500"
        placeholder={"Name"}
        onChange={(e) => props.setData(e.target.value)}
        value={props.data}
        {...(!props.isTrue && "disabled")}
        // here (below) it works fine but it is permanently disabled option
        //   disabled
      />
    </>
  );
}

The solution of this which i got form the attached (Conditional disabling of button) question is:

export function InputFiled(props) {
  return (
    <>
      <input
        className="py-2 pl-3 rounded-[14px] border-[1.3px] border-red-500"
        placeholder={"Name"}
        onChange={(e) => props.setData(e.target.value)}
        value={props.data}
        disabled={props.isTrue? true : false}
        />
    </>
  );
}


Solution

  • You may need to set additional tailwind css classes based on this state or prop which you want to baseline.

    const [isDisabled, setDisabled] = useState(false);
    //inside render
    <input type='button' 
     onClick={(e)=> setDisabled(!isDisabled)}
     disabled={isDisabled}
    >