Home > other >  How can I prevent certain characters from being deleted from a React input tag?
How can I prevent certain characters from being deleted from a React input tag?

Time:02-23

I would like to know how to prevent a specific string from being erased even if I press backspace from the input passed the value.

product : [none_fix]changeValue

I want to prevent the [none_fix] part from being erased even if I press backspace.

CodePudding user response:

By making your input a Controlled Component, you can decide what value the input displays. Put whatever logic you need in the input's onChange handler - so in this case, don't propagate changes that would result in the UNERASABLE_TEXT being deleted:


const UNERASEABLE_TEXT = "[none_fix]";

export default function App() {
  const [controlledValue, setControlledValue] = useState(UNERASEABLE_TEXT);

  const onInputChanged = (e) => {
    const newValue = e.target.value;
    // Only allow changes that retain the magic string:
    if (newValue.startsWith(UNERASEABLE_TEXT)) {
      setControlledValue(newValue);
    }
  };

  return <input onChange={onInputChanged} value={controlledValue} />;
}


  • Related