React Native: How to focus a TextInput wrapped in a custom component?

Viewed 2326

In my React Native app I have a custom component that wraps a TextInput. In the code that uses the custom component, I want to call .focus() on the TextInput. I tried calling it directly on the custom component like this:

<CustomComponent
  ref={ref => {
    this.customComponent = ref;
  }}
/>

this.customComponent.focus();

but I can't because, I assume, custom components don't have a focus() method. I could find a way to call it on the wrapped TextInput, but I'm wondering if there's a way to call it directly on the custom component.

Does anyone know how I can approach this?

2 Answers

if a class component you could use CustomComponent.prototype.yourFunction()

youFunction uses ref to call focus() on TextInput

If CustomComponent is your own component then in that case you can pass the ref via Forwarding Refs :


Here I have created sample code snippets, which has input inside CustomComponent and we can access ref inside that component via React.forwardRef((props, ref)

Then we have createRef from parent component and pass ref like <CustomComponent ref={this.ref}>.

Hope this will help you.

const CustomComponent = React.forwardRef((props, ref) => (
  <div>
    <input type="text" ref={ref} />
  </div>
));

class App extends React.Component {
  constructor(props) {
    super(props);
    this.ref = React.createRef();
  }
  componentDidMount() {
    if(this.ref.current) {
      this.ref.current.focus();
    }
  }
  
  render() {
    return (
      <div>
        Get Focused : 
        <CustomComponent ref={this.ref} />
      </div>
    );
  }
  
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>

Related