0

For some reason, the focus on my input field keeps getting lost whenever there is any change. I have already tried different approaches like passing the value through both value or useRef, but nothing helped. Initially, the problem occurred when I started rendering my component not as a function (because I couldn't use hooks there) but as a regular JSX component. However, this change needs to remain, and I need to do something to fix this issue. I could manually set the focus whenever formik.values.key1 changes, but that is not a solution either because there is a blue border around this input that will constantly change as a result.

upd: i use some mask here inputRef.current.value = props.formik.values.key1 || "";, i need to add some spaces between the numbers and this is why i need to refresh value after any change

Could you please help me with this issue?

export const Component = (props : any) => { 


  const inputRef = React.useRef<HTMLInputElement>(null);

  const handleChange: ChangeEventHandler<string | undefined> = (event) => {
    const { value } = event.target;
    props.formik.setFieldValue("Additional_JKSO", value?.replace(/[^0-9]/g, ""));
  };

  React.useLayoutEffect(() => {
    if (inputRef.current) {
      inputRef.current.value = props.formik.values.key1.replace(/^(.{3})(.{0,2})(.{0,2}).*$/, formateFunction) || "";
    }
  }, [props.formik.values.key1]);

  if (props.fieldSchema.fieldKey == "key1"){
    return <div className="flex">
      <div className="text-box">
        <input className="text-box__input" maxLength={9} onChange={handleChange} disabled={disabled} ref={inputRef} />
      </div>
    </div>;
  }
NoOneCare
  • 51
  • 5
  • Does your input lose _focus_ or the _caret position_? – Martin Jun 06 '23 at 11:03
  • 1
    If something is re-rendering your component, you will lose focus. I'm pretty certain Formik uses react state and so any updates/changes to that state will trigger a re-render (setFieldValue/setFieldTouched etc). https://stackoverflow.com/questions/22573494/react-js-input-losing-focus-when-rerendering – Vayne Valerius Jun 06 '23 at 11:41

0 Answers0