DEV Community

Cover image for Two Quick IHP tips to dynamically assign classes
digitallyinduced
digitallyinduced

Posted on

4 3

Two Quick IHP tips to dynamically assign classes

Here are two quick tips for IHP:

Use the classes helper

...to dynamically assign classes to elements in your views. It's an easy way to simplify your code by a lot:

-- BEFORE
<a class={usersLinkClasses} href={UsersAction}>Users</a>
<a class={invitesLinkClasses} href={InvitesAction}>Invites</a>
...
where
    usersLinkClasses = "nav-link" ++ if isActivePath UsersAction
        then " active"
        else ""
    invitesLinkClasses = "nav-link" ++ if isActivePath InvitesAction
        then " active"
        else ""

-- AFTER
<a class={classes ["nav-link", ("active", isActivePath UsersAction)]} href={UsersAction}>Users</a>
<a class={classes ["nav-link", ("active", isActivePath InvitesAction)]} href={InvitesAction}>Invites</a>
Enter fullscreen mode Exit fullscreen mode

Use isActivePathOrSub instead of isActivePath

If you read the previous example, you might have noticed that I used isActivePath to dynamically assign the active class to the links. Well, using isActivePathOrSub this will also work if the path is a sub-path. In the following example, both /Settings and /Settings/Profile would match and cause the link to get the active class. Learn more in the documentation.

<a class={classes ["nav-link", ("active", isActivePathOrSub "/Settings")]} href={SettingsAction}>Settings</a>
Enter fullscreen mode Exit fullscreen mode

If this peaked your interest, get started with IHP now and tell us what you think!

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

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

Okay