Focus the Input automaticly in a react way every time I refresh the page

Viewed 440

I can focus the input by get the element By ID, but is there a standard react way to do it?

function App() {

  useEffect(() => {

    let myInput = document.getElementById('myInput');
    myInput.focus()
  })


  return (
    <div className="App">
      <input id="myInput" placeholder='your name'/>
    </div>
  );
}
2 Answers

Using useRef you can do it !

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

function App() {
  const inputTxt = useRef(null)
  useEffect(() => {
    inputTxt.current.focus()
  })


  return (
    <div>
      <input type='text' />
      <input ref={inputTxt} />
    </div>
  );
}
export default App;

We should never get DOM elements as these references might later give rise to memory leaks. You could create a ref object and pass it to the input component and then use it later. For example:

function App() {
const inputRef = React.useRef<HTMLElement>(null);

  useEffect(() => {
    inputRef.current.focus();
  })


  return (
    <div className="App">
      <input id="myInput" placeholder='your name' ref={inputRef}/>
    </div>
  );
}

Please read this doc for further information: https://reactjs.org/docs/refs-and-the-dom.html

Related