Text-mask: Component isn't setting its ref

Created on 22 Nov 2017  路  5Comments  路  Source: text-mask/text-mask

I'm trying to set focus in a MaskedInput, however looks like that the prop ref isn't being set.

As reference I have this React example:

````
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focusTextInput = this.focusTextInput.bind(this);
}

focusTextInput() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}

render() {
// Use the ref callback to store a reference to the text input DOM
// element in an instance field (for example, this.textInput).
return (


ref={(input) => { this.textInput = input; }} />
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>

);
}
}
````

Always when I try to call the method focusTextInput it shows that the textInput is null and cannot set focus()

Anyone already tried or needed to set focus on MaskedInput?

Most helpful comment

This ref is available via like this

ref={(input) => { this.textInput = input; }}

You can then access the raw DOM node via input.inputElement as the react source already adds a ref the the underlying <input ... /> or use ReactDOM.findDOMNode on this.textInput, but you really don't need to in this case.

https://github.com/text-mask/text-mask/blob/master/react/src/reactTextMask.js

All 5 comments

Did you manage to find a solution?
UP!

This ref is available via like this

ref={(input) => { this.textInput = input; }}

You can then access the raw DOM node via input.inputElement as the react source already adds a ref the the underlying <input ... /> or use ReactDOM.findDOMNode on this.textInput, but you really don't need to in this case.

https://github.com/text-mask/text-mask/blob/master/react/src/reactTextMask.js

I'm unable to use ref to get the input, using findDOMNode worked.

this.textInput.inputElement is the answer you're looking for. Instead of the element being available at this.textInput or at ref.current, you need to add .inputElement. It's annoying but it worked for me.

You can also hack your way through it like this, the component exposes a render prop:

const ref = useRef();
return (
  <MaskedInput
    render={(textMaskRef, props) => (
      <input
        {...props}
        ref={node => {
          textMaskRef(node); // Keep this so the component can still function
          ref.current = node; // Copy the ref for yourself
        }}
      />
    )}
  />
);

Was this page helpful?
0 / 5 - 0 ratings

Related issues

intellix picture intellix  路  4Comments

AliveDD picture AliveDD  路  5Comments

gabrielamarques picture gabrielamarques  路  6Comments

ktriek picture ktriek  路  3Comments

KevinGruber picture KevinGruber  路  6Comments