Reputation: 1203
I have a text which was earlier wrapped in an H1 tag. I need to focus on that text once my page is loaded. I wrapped it in a div for my convenience.
render() {
const { translate, billing: { primaryContactSelection = true } } = this.props;
return (
<div {...resolve(BillingStyles, 'billingContainer')}>
<div id="mainHeader"><h1 {...resolve(BillingStyles, 'mainHeader')}>
{translate('PanelBillingHeadingText')}
</h1> </div>
<div {...resolve(BillingStyles, 'billingInfoContainer')}>
......
......
</div>
</div>
);
}
}
I have tried the below code:
componentDidMount() {
console.log('Component Did Mount .............');
document.getElementById('#mainHeader').focus();
}
But it is not focusing on the div.
Upvotes: 5
Views: 13419
Reputation: 1241
First div
elements are not focusable by default so you need to give it a tabIndex:
render() {
const { translate, billing: { primaryContactSelection = true } } = this.props;
return (
<div {...resolve(BillingStyles, 'billingContainer')}>
<div tabIndex="0" id="mainHeader"><h1 {...resolve(BillingStyles, 'mainHeader')}>
{translate('PanelBillingHeadingText')}
</h1> </div>
<div {...resolve(BillingStyles, 'billingInfoContainer')}>
......
......
</div>
</div>
);
}
}
Next make sure you don't include the hashtag when calling getElementById, so it should be :
componentDidMount() {
console.log('Component Did Mount .............');
document.getElementById('mainHeader').focus();
}
And that should work from there.
Upvotes: 13
Reputation: 114
When you use getElementById function you don't need #
sign inside braces.
Upvotes: 1