Reputation: 584
I need to trigger a .focus()
in a button, on a React component. But it comes from a 3rd party library and I can't use ref
.
The only way I managed to do so far is by using setTimeout AND querySelector 😬, as the element is not immediately available upon componentDidMount
. Bellow is my current code:
componentDidMount() {
window.setTimeout(() => {
const confirmButton = document.querySelector('.confirmButton');
confirmButton && confirmButton.focus();
}, 1);
}
Is there any other less ugly way of achieving that?
Upvotes: 4
Views: 241
Reputation: 584
I realized I can send native props to the Button component 😅
- componentDidMount() {
-
- window.setTimeout(() => {
- const confirmButton = document.querySelector('.confirmButton');
- confirmButton && confirmButton.focus();
- }, 1);
- }
-
...
<Button
+ autofocus
Upvotes: 1