tabIndex to focus on inner React component inside anchor tag

Viewed 5440

I am trying to add a 'Skip to main content' accessibility button that receives focus on a page when a user hits tab.

I would like to wrap already existing React components (Button, Card) in an anchor tag and then upon hitting tab, focus solely on the most inner component (Button) and navigate to the anchor tag href upon hitting 'Enter'.

My code is as follows:

<a href="/get-started" className="link link--list-item link--skip-link">
  <Card className="card--skip-link">
    <ButtonText Icon={IconArrowRight} iconPosition="right">
    Skip to main content
    </ButtonText>
  </Card>
</a>

As the code stands, the focus state is applied to the whole anchor tag. I would like to apply the focus state to ONLY the button (the button is smaller than the card that contains it).

When I add tabIndex="-1" to the anchor tag and tabIndex="0" to the Card and/or Button, the elements are not selected at all when tabbing through.

My CSS is:

.link {
  &--skip-link {
    position: absolute;
    top: -10000px;
    left: -10000px;
    height: 1px;
    width: 1px;
    text-align: left;
    overflow: hidden;

    &:active,
    &:focus,
    &:hover {
        top: 10%;
        left: 40%;
        width: auto;
        height: auto;
        overflow: visible;
        color: black;
    }
  }
1 Answers

The tabindex should actually work and i can also be caused since the css focus selector is added to link and not card.If this doesn't work then after selecting tab check

document.activeElement() and check which element is focused when the following code is applied.

  <a href="/get-started" className="link link--list-item link--skip-link" tabindex="-1">
  <Card className="card--skip-link" tabindex="0">
    <ButtonText Icon={IconArrowRight} iconPosition="right"
Skip to main content
    </ButtonText>
  </Card>
</a>




 .card {
  &--skip-link {
    position: absolute;
    top: -10000px;
    left: -10000px;
    height: 1px;
    width: 1px;
    text-align: left;
    overflow: hidden;

    &:active,
    &:focus,
    &:hover {
        top: 10%;
        left: 40%;
        width: auto;
        height: auto;
        overflow: visible;
        color: black;
    }
  }
Related