Home > Software engineering >  Auto focus first time on loading page
Auto focus first time on loading page

Time:11-26

There is a input text in center in which I want to focus when the page loads, so I have used componentDidMount() and set the focus.

componentDidMount() {
 this.inputBar.focus();
}
.
.
<input type="text" ref={(element) => { this.inputBar = element; }}>

but it isn't working as a sidebar pops in as the page loads and shifts the focus from the center input. I tried to use componentDidUpdate() but then it triggers the focus again and again when I close the sideBar. I only want to focus only at first time when I load the page. I am new at coding, please suggest something that can be done here. Thanks in advance.

CodePudding user response:

If you want to focus a single Input then you can simply do

<input type="text" autofocus>

CodePudding user response:

If you just want to focus an element when it mounts (initially renders) a simple use of the autoFocus attribute will do.

<input type="text" autoFocus />

Or if you want to do it with componentDidMount and to control focus dynamically you can go with the below snippet

class App extends React.Component{
      componentDidMount(){
        this.nameInput.focus();
      }
      render() {
        return(
          <div>
            <input defaultValue="Won't focus"/>
            <input ref={(element) => { this.nameInput = element; }} defaultValue="will focus"/>
          </div>
        );
      }
    }
        
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related