How to use the React useRef hook with the Numberformat component?

Asked

Viewed 73 times

2

I am using the lib react-number-format to take a value as formatted currency in my form and then save it to a state. Currently it is this way:

<NumberFormat
      thousandSeparator={true}
      value={form.valor}
      placeholder="R$ ao dia"
      onValueChange={(values) => {
           const { value } = values
           setForm(prev => ({ ...prev, valor: value }))
           }}
      prefix={'R$'}
              />

It works great, but I’d like to take the input reference with the hook useRef do React, but I don’t know how I would do that on that particular component. I tried that only it didn’t work:

const inputRef = useRef(null)

<NumberFormat
       ref={inputRef}
       thousandSeparator={true}
       placeholder="R$ ao dia"
       prefix={'R$'}
 />

When I soon inputRef.current.value comes Undefined. Someone knows how to get the reference of this mask?

1 answer

3


According to the documentation of the component itself, such as ref is a special property of React, you are taking the component reference NumberFormat, and not of input.

To get the reference of the input, you can use the prop getInputRef:

<NumberFormat getInputRef={inputRef} />
// <NumberFormat getInputRef={(el) => this.inputElem = el} />

The documentation further cites that if you use a custom input, you should take the reference in another way:

<NumberFormat inputRef={inputRef} customInput={TextField} />
// <NumberFormat inputRef={(el) => this.inputElem = el} customInput={TextField} />

Now that you have the correct reference to the input, you can get the value :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.