My code below works but the this.buttonRef.current.firstChild.focus()
stops working if it's not in a setTimeout function.
From looking at the official docs for refs I cant see why this is happening. Is there anything obviously wrong with my component? If not Im wondering if another component on my site is 'stealing' focus as when the url
prop changes a modal is closed.
UPDATE: One weird thing is if I console.log
outside of the setTimeout then I can see the element is present in the DOM.
UPDATE2: Turns out it was React Trap Focus in my modal that was causing the issue. Removing the focus trap means I don't need the timeout. As I need the focus trap I think the setTimeout will need to stay.
https://github.com/davidtheclark/focus-trap-react
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.buttonRef = React.createRef();
}
componentDidUpdate(prevProps) {
if (this.props.url === '' && prevProps.url = "old-url") {
console.log('target element: ', this.buttonRef.current.firstChild)
// This doenst work if not in a setTimeout
// this.buttonRef.current.firstChild.focus();
setTimeout(() => {
this.buttonRef.current.firstChild.focus();
}, 1);
}
}
render() {
const {
limitIsReached,
add
} = this.props;
return (
<Fragment>
<Title>My title</Title>
<Section>
<Button>
Add a promo code
</Button>
<span ref={this.buttonRef}>
{limitIsReached ? (
<Alert
message="Sorry limit reached"
/>
) : (
<Button
onClick={add}
>
Add new
</Button>
)}
</span>
<List compact />
</Section>
</Fragment>
);
}
}
export default MyComponent;