DEV Community

Brian Barbour
Brian Barbour

Posted on

Tip: Disabling Links As Buttons in Gatsby

I was working on my Gatsby blog project today and ran into a little quirk. I wanted navigation buttons to let the user go to the next and previous posts in the blog. I wanted those buttons to be Gatsby Links. Simple enough, right? However, when the user reaches the very first post or the very last, I wanted said button links to be disabled.

For example:

        <Link
          disabled={!nextPost}
          className="button"
          to={nextPost ? nextPost.node.fields.slug : "/"}
        >Next Post</Link>
Enter fullscreen mode Exit fullscreen mode

See, if nextPost is falsy, the Link should be disabled. Except, in practice I found that despite it appearing disabled it still can be clicked and fired off. And it will sling them to the index page of the site.

After a little digging around Google, I figured out this neat trick. It required I add this class to my CSS.

.disabled-link {
  pointer-events: none;
}
Enter fullscreen mode Exit fullscreen mode

After that I just needed a ternary statement put this before the component's return JSX.

 const disabledNext = nextPost ? "" : "disabled-link"
Enter fullscreen mode Exit fullscreen mode

To finish, I morphed my Link button into this:

        <Link
          disabled={!nextPost}
          className={`button ${disabledNext}`}
          to={nextPost ? nextPost.node.fields.slug : "/"}
        >Next Post</Link>
Enter fullscreen mode Exit fullscreen mode

The .disabled-link CSS class makes it so it can't be clicked at all, returning the disabled functionality to it that I intended. Bing, bang, boom!

Top comments (2)

Collapse
 
dance2die profile image
Sung M. Kim

That is a nice trick.

Never knew that pointer-events has been available for awhile.

caniuse.com/#search=pointer-events

Collapse
 
feldev profile image
FĂ©lix Paradis

Your links are still "clickable" via keyboard navigation though, right?