renato-bohler/redux-form-input-masks

Doesn't apply mask initially

Closed this issue · 2 comments

What are you reporting?

  • Bug
  • Feature request
  • Code refactor
  • Continuous Integration (CI) improvement
  • Changes in documentation (docs)
  • Other (describe)

What is the current behavior?

It doesn't create mask when using initialValues of redux-form. I have to focus in and out to see mask.

What is the expected behavior?

It should show mask without user have to focus manually to see it.

Sandbox Link

What's your environment?

Mac os high sierra 10.13.3

Other information

I'm assuming this is happening for text masks, when you have stripMask set to false and your initial value isn't formatted. Is that the case?

issue

I've investigated this issue today @ninjarails.

Unfortunately, it is technically impossible to solve it on the library side. We could set the formatted value on the input, but the stored value would be not formatted until the user focuses in and out. This is because redux-form only calls normalize when the input value has changed, and we can't force that to happen.

This is the best that we can do, and it's just not enough:

issue26


There is a simple solution to this, though. You can normalize your Field's initialValue if it isn't coming formatted and you want to store it formatted, something like this:

const notStrippedMask = createTextMask({
  pattern: "(999) 999-9999",
  stripMask: false
});

// (...)

export default reduxForm({
  form: "textMask",
  initialValues: {
    // Stripped initial value for not stripped mask
    notStripped: notStrippedMask.normalize("1234567890")
  }
})(CreateTextMask);

I've made a codesandbox example implementing that.

I'm closing this for now, if you have any questions you can open it again. Thanks for reporting the issue!