DEV Community

Brian Barbour
Brian Barbour

Posted on

4 2

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!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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?

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay