Search code examples
reactjsfocuspageload

react way of setting focus on a particular button in stateful component?


I tried different ways of setting focus to button on pageload like ref ,but it doesnt work. Thats is whenever pageloads focus should be on this button. Can anyone help me with a sample example

class SubPageHeader extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {

  }
  render() {
   return (
    <input type="button"/>
   );
  };
}

Can anyone help me with a solution ?


Solution

  • componentDidMount will execute only once when your page loads first time, to maintain a focus on every re-render you also need to use componentDidUpdate.

    class SubPageHeader extends React.Component {
      constructor(props) {
        super(props);
        this.myInput = React.createRef();
      }
    
      componentDidMount() {
         this.myInput.current.focus(); //To focus first time page loads
      }
    
      componentDidUpdate(){
         this.myInput.current.focus(); //To focus on every re-render
      }
    
      render() {
        return (
          <input type="button" ref={this.myInput} />
        );
      };
    }