0

In my parent component constructor (class based), I add a ref for an input field by using:

this.usernameRef = React.createRef();

This works just fine in the parent component. For example, the following works fine:

 const username = this.usernameRef.current.value; // this works

I'm passing .focus() call to the ref into a child component like so:

<ChildComponent
    onClick={() => this.usernameRef.current.focus()}
/>

In my child component, it gets called with an onClick event:

<a href="#" onClick={onClick} />

While the app is running, when I click on that link, I get the following error:

e.usernameRef.current.focus is not a function

Should I be going about this a different way?

For what it's worth, the child component is function based.

Thanks

user1702965
  • 379
  • 5
  • 16
  • Something is off between the code you showed us and the error you are getting: `this.usernameRef.current.focus()` or `e.usernameRef.current.focus()`? – Martin Nov 23 '21 at 09:39

1 Answers1

0

In React we have to use React.forwardRef

In the example below, FancyButton uses React.forwardRef to obtain the ref passed to it, and then forward it to the DOM button that it renders:

const FancyButton = React.forwardRef((props, ref) => (  <button ref={ref} className="FancyButton">    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
owenizedd
  • 1,187
  • 8
  • 17