1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Customize Styles for Partially Matched URLs With Gatsby’s Link Component

    Jason LengstorfJason Lengstorf
    gatsbyGatsby

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    This is a great way to make sure that parent nav items stay highlighted even when subsections of the pages are being accessed.