You can prevent changing the input value prefix in the onChange
callback:
const {useState} = React;
const Component = ({defaultText}) => {
const [text, setText] = useState(defaultText);
const onChangeText = (e) => {
if (e.target.value.substr(0, defaultText.length) === defaultText)
setText(e.target.value);
}
return (
<div>
<input onChange={onChangeText} value={text} />
</div>
)
}
ReactDOM.render(<Component defaultText='ABC'/>, document.querySelector("#app"))
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
input {
margin-right: 5px;
}
<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="app"></div>
UPD: For Redux Form Field
use:
import React, {useState} from "react";
import { Field } from "redux-form";
const defaultText = "ABC";
const TextWithPrefix = () => {
const [text, setText] = useState(defaultText);
const onChangeText = (e) => {
if (e.target.value.substr(0, defaultText.length) === defaultText)
setText(e.target.value);
};
return (<input onChange={onChangeText} value={text} />);
};
const FormComponent = ({ handleSubmit, onSubmit }) => {
return (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<Field component={TextWithPrefix} />
</form>
</div>
);
};