Search code examples
reactjsonclickreadonlyinputbox

Remove Readonly when it is clicked outside of the input in React


I am trying to handle with read-only on my input component. So basically, I have an input component and as default, it comes with read-only. What I am trying to do is when it is clicked inside of the input field, read-only comes false and it is editable. But I want read-only true again, only when it is clicked to the outside of the input box. So here is my component:

const InputComponent = () => {
  const [disabled, setDisabled] = useState(true);

  function handleClick() {
    if(disabled == true) {
      setDisabled(false);
    }
    else {
      //TODO: click outside the set readonly
    }
  }

  return (
    <Form.Control type="number" readOnly={disabled} onClick={handleClick}/>
  );
};

So my logic is quite simple when, disabled is true that means read-only is true so when it is clicked inside, disabled turns false and it is being editable. But I couldnt do the rest. So I dont know how to make disabled false again when it is clicked outside.

Thanks for your help. And I am open more idea.


Solution

  • You can use onBlur to do that:

    <Form.Control onBlur={() => {setDisabled(true)}} />