s-yadav / react-number-format

React component to format numbers in an input or as a text.
MIT License
3.9k stars 410 forks source link

Losing focus on input when using a Bootstrap input label #785

Closed barrychapman closed 1 year ago

barrychapman commented 1 year ago

Describe the issue and the actual behavior

When entering text in the field, the field immediately clears, and loses focus - suspecting rerender. I am using function based components

Describe the expected behavior

Not lose focus, and update accordingly

Provide a CodeSandbox link illustrating the issue

https://codesandbox.io/s/crimson-https-zqvd27?file=/src/App.js

Provide steps to reproduce this issue

type in box, observe

Please check the browsers where the issue is seen

s-yadav commented 1 year ago

The problem is your are passing inline function on customInput, customInput accepts a Component reference (note it's not a render prop), here you are passing new component reference every time it rerenders. This makes it umount and remount CustomInput every time it renders loosing focus and state.

customInput={() => (
            <CustomInput
              labelClass={labelClass}
              placeHolder={placeHolder}
              maxlength={maxlength}
              selfOnChange={selfOnChange}
              value={value}
              isValid={isValid}
            />
          )

All the additional props are forwarded to customInput. so you don't need to create an inline function instead can do.

<PatternFormat
          format={mask}
          allowEmptyFormatting={false}
          mask={""}
          labelClass={labelClass}
          placeHolder={placeHolder}
          maxlength={maxlength}
          selfOnChange={selfOnChange}
          value={value}
          isValid={isValid}
          customInput={CustomInput}
        />

Here's an updated sandbox. https://codesandbox.io/s/compassionate-gates-nlz37j

s-yadav commented 1 year ago

I will also add this note in the doc to avoid future confusion.