When viewing pages that partially match the to
prop in a Gatsby Link
component, it’s often desirable to show that page as “active”, such as when viewing an anchor link to a heading on the page, or showing the “blog” link as active when viewing /blog/my-great-post/
. This video will show you how to pass a function to getProps
and identify partial matches using the isPartiallyCurrent
prop.
Instructor: [00:00] In order to keep the active state for a link to decisions that has an anchor, or in the event of a blog where it was /blog/ the name of your blog post, we need to use something called partial matching. In Gatsby, we do this by accessing the props of the current nav item.
[00:21] Here, we're able to pass a function. That function gets props about the current link from Reach Router. We're going to see if part is-partially-current is true. Is partially-current comes back if any section of the two-prop matches the current path.
[00:42] What we can do is, we can say, if is-partially-current, then we're going to return a style prop. If not, we're going to return nothing. I'm going to save that, make it a little easier to read.
[00:59] Now in here, we get to override the style prop entirely, which means that we need to keep our link styles, so we can just spread those in. We also want to put in the active styles, so we're going to spread those in as well.
[01:14] Upon saving, we should see that even with our anchor, we still get the active state. Without the anchor, we're getting the active state as well.
[01:27] This is a great way to make sure that parent nav items stay highlighted even when subsections of the pages are being accessed.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!