0

How can i put a default text in an Redux Form Field which user can't delete (fixed text on start of the input).

The second thing what i want that the cursor will be indexed after this fixed text.

For not using redux: Html Put a fixed text on an input text

dnsakjdnk
  • 1
  • 2

1 Answers1

0

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>
  );
};
Michael Rovinsky
  • 6,807
  • 7
  • 15
  • 30