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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With