2

I am trying to use a ref to get to the underlying input element of an InputText component. I used this.textFieldRef = React.createRef() to set up the ref, and then the attribute ref={this.textFieldRef} to hook it up. Yet in the componentDidMount I cannot use this.textFieldRef.current.select() because select() is not a function available for that object. So somehow, InputText is not returning the underlying HTMLInputElement.

Does anyone know how I can get from a ref to something that allows me to select() the text in the InputText element?

Here is my code, which is actually in TypeScript...

import * as React from 'react';
import { InputText } from 'primereact/inputtext';

export class ValueCard extends React.Component<{}, {}> {

  textFieldRef: React.RefObject<any> = React.createRef();

  componentDidMount = () => {
    if (this.textFieldRef.current instanceof InputText) {
      this.textFieldRef.current.select();
    }
  }

  render() {
    return = (
      <InputText
        value="test"
        ref={this.textFieldRef}
      />
    );
  }
}
EFC
  • 1,890
  • 18
  • 39

2 Answers2

1

Looking at the source for PrimeReact's InputText component (source), they are attaching a reference to the inner input element to this.element. This allows you to just add .element to your reference:

this.textFieldRef.current.element.select();

I tested it out in this sandbox, and it seems to work as expect: https://codesandbox.io/s/203k7vx26j

Matty J
  • 988
  • 9
  • 13
1

Maybe you could try to use react-dom library:

ReactDOM.findDOMNode(this.textFieldRef.current).querySelector('input');
Przemek Nowicki
  • 572
  • 4
  • 7