Material-UI: Restrict users from removing first characters in a TextField

Viewed 26

I'm working with a TextField in Material UI. I need to restrict the user from deleting the first few words (initialValue) of a TextField. This is to ensure user responses start with specific text which is necessary in this case. Is this possible?

const initialValue = "This taught me"

const [response, setResponse] = useState(initialValue);

<TextField  
multiline
minRows={3} 
onChange={e => setResponse(e.target.value)}
value={response}
autoFocus={true}
inputRef={textInput}
/>
1 Answers

Converting my comment to an answer.


Instead off calling setResponse right away, call a custom function with some logic:

  1. If the new value is shorter then initialValue, set initialValue as value
  2. If the new value does not startsWith() initialValue, set the value again to the initialValue

// Get a hook function
const {useState} = React;

const Example = () => {
  
    const initialValue = "This taught me"
    
    const [response, setResponse] = useState(initialValue);
    
    const onInput = (val) => {
      if (val.length < initialValue.length || !val.startsWith(initialValue)) {
        setResponse(initialValue);
      } else {
        setResponse(val)
      }
    }
    
    return (
        <div>
            <input value={response} onChange={(e) => onInput(e.target.value)} />
        </div>
    )
}
ReactDOM.render(<Example />, document.getElementById("react"));
input { min-width: 300px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Related