Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus on a button when react component renders?

Tags:

reactjs

I want to set focus on a button as soon as the react component loads, so that the user can just use the keyboard to press the button.

This is what I was trying to do, but this does not seem to work.

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.logButton = React.createRef();

  }

  componentDidUpdate(){
     this.logButton.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <Button ref={this.logButton}  outline color="primary" size="sm" onClick={this.logManualRequestModal}>
         Log request
        </Button>
      </div>
    );
  }
}

and I'm using tabler-react component

like image 976
Shubhang Arora Avatar asked May 14 '26 17:05

Shubhang Arora


1 Answers

Change componentDidUpdate() to componentDidMount() like below:

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

and your using Button component from tabler-react and Button component ref defined as rootRef check their props for ref in Button Component.

So change ref like this :

<Button rootRef={this.logButton} color="primary">A Button</Button>

demo and ref

like image 138
Jayavel Avatar answered May 16 '26 06:05

Jayavel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!