0

I found this answer: ReactJS and autofocus

but I don't know how to convert this:

constructor(props) {
    super(props);
    this.myRef = React.createRef();
}

componentDidMount(){
  this.myRef.current.focus();
}

<input type="text"  ref={this.myRef} />

to react hooks version.

I tried doing this:

const myRef = () => {
  React.createRef().current.focus();
}

<input type="text"  ref={myRef} />

but got error:

TypeError: Cannot read property 'focus' of null

1 Answers1

0

As well as useRef you'll need to use useEffect too which runs after a render. The [] means that it only runs once.

import React, { useRef, useEffect } from 'react';

function Component() {

  const ref = useRef(null);

  useEffect(() => {
    ref.current.focus();
  }, []);

  return <input type="text"  ref={ref} />;

}
Andy
  • 61,948
  • 13
  • 68
  • 95