In-page hash navigation does not set focus
See original GitHub issueI have initially logged this as an issue on the gatsby-mdx repo here;
Describe the bug When I click an anchor that refers to a location inside the page, the destination element does not receive proper focus. Although the browser scroll position is reset properly, the destination element is not read out by screen readers as it does not receive focus correctly.
To Reproduce
- Clone repository https://github.com/AlmeroSteyn/gatsby-mdx-minimal-repro
- Go to homepage
- Click on the link right at the top named
Skip to content
- Note how the container below with the text
This is some content
does not get a focus outline. - Now go to route
/focus
which is a straight React component withoutMDX
. - Click on link right at the top named
Skip to content
- Note how the container below with text
This is some content
DOES get a focus outline on this page.
Both of these pages uses te same Layout
component that contains the link and in-page navigation destination. When used in an MDX
file it doesn’t work, while using it as a straight page component does work
When I was looking into why this was happening I noticed that on the MDX
pages the entire content is remounted even when the hash portion of the URL changes. This breaks the standard browser behaviour of setting focus to the target element.
Because focus is not set correctly, screen readers will not announce to the users that any action has been performed.
During triage of the issue on the gatsby-mdx
repo it was found that setting a shouldComponentUpdate
flag based on the location.hash
value on the MDXTag
component will fix the issue in some cases. However the following cases should work and properly set focus to the element in question:
- Clicking a hash anchor when the browser URL is not set to the hash location.
- Clicking a hash anchor when the browser URL was set before by a previous click.
- Refreshing a page when the browser URL already contains the hash.
Expected behavior
Navigating to an element with an id
corresponding to the hash in the href
of the anchor should set focus on the element to allow screen reader users to also use applications built with MDX
.
Issue Analytics
- State:
- Created 5 years ago
- Comments:32 (18 by maintainers)
Top GitHub Comments
@silvenon I’d like that yes! Next week sometime?
I’m terribly sorry to hear that. When you have time I’d like to pair with you to solve the development environment, because the point of that setup was to minimize the friction of enforcing a code style.
Thanks for writing the docs here, your great! I’ll set you as the author when I’m committing the changes, so it should still show up as your contribution.