1

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 ?

3 Answers 3

1

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} />
    );
  };
}
Sign up to request clarification or add additional context in comments.

Comments

1

Using refs:

class Component extends React.Component{
    input = React.createRef()

    componentDidMount(){
        this.input.current.focus()
    }

    render(){ return <input ref={this.input} /> }
}

Or plain HTML : <input autoFocus />

Comments

1

To focus on component mount the simplest way is

class SubPageHeader extends React.Component {

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.