Home > Net >  How do I prevent a user from being able to type or click in an input field? [React]
How do I prevent a user from being able to type or click in an input field? [React]

Time:12-09

A bit of an odd request, but I'm looking for a way to have an input field be completely un-interactable with.

I have a component with an input field that the user should interact with. In another page of my app, I want to reuse the visual of that component, but they should not be able to interact with it.

I have tried:

<input
       type="text"
       placeholder="[Click here to enter scramble you want to solve]"
       onClick={(e) => e.preventDefault()}
/>

But it did not work.

CodePudding user response:

Add a prop for disable the input based on parent component where you want to use

<input
       type="text"
       placeholder="[Click here to enter scramble you want to solve]"
       onClick={(e) => e.preventDefault()}
      disabled={props.disabled}
/>

CodePudding user response:

Try readonly inside input field, it might work for you

<input readonly type="text">

CodePudding user response:

To make an input field un-interactable, you can use the disabled attribute. This attribute disables the input field, preventing the user from typing in it, clicking on it, or otherwise interacting with it. Here's an example:

<input
  type="text"
  placeholder="[Click here to enter scramble you want to solve]"
  disabled
/>

Alternatively, you can use the readOnly attribute to make the input field read-only. This means the user can see the value of the input field, but they cannot change it. Here's an example:

<input
  type="text"`enter code here`
  placeholder="[Click here to enter scramble you want to solve]"
  readOnly
/>

Note that you can also use the style attribute to make the input field appear un-interactable by setting the cursor property to default or not-allowed, like this:

<input
  type="text"
  placeholder="[Click here to enter scramble you want to solve]"
  style={{ cursor: 'not-allowed' }}
/>

However, this approach does not actually prevent the user from interacting with the input field, so it's not recommended for situations where you want to completely prevent user interaction.

  • Related