DEV Community

loading...
Cover image for Two Quick IHP tips to dynamically assign classes

Two Quick IHP tips to dynamically assign classes

digitallyinduced
We're digitallyinduced - the company behind IHP, the fastest growing Haskell Web Framework! We aim to make development magical (again)!
・1 min read

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!

Discussion (0)