Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Active className for <A>? #20

Open
supun-io opened this issue Dec 28, 2021 · 3 comments
Open

Active className for <A>? #20

supun-io opened this issue Dec 28, 2021 · 3 comments

Comments

@supun-io
Copy link
Contributor

supun-io commented Dec 28, 2021

As far as I understood, there is no way to add a className for active <A>s (like React-router's <NavLink>).

Is this something in the roadmap? I'm happy to add a pull request if that's something worth adding to the library.

@mariusandra
Copy link
Member

Hey, you can use className with the <A> tag. All props other than onClick get copied to the regular <a> tag directly.

@mariusandra
Copy link
Member

Apologies for the hasty comment, I see what you mean now.

I'd be happy to add this to the library. Feel free to send a PR. Just keep in mind that it should also be a separate tag (wrapper over A probably), and not just a prop you can toggle. That's because such a link needs to call useValues, which adds a subscription that watches for changes in the state. Some users might have thousands of <A> tags, and it's best not to slow down the default behaviour.

@supun-io
Copy link
Contributor Author

supun-io commented Jan 4, 2022

Yes, it requires a subscription to the router state - so not inexpensive, but can be useful for things like main navigation.

I wrote a component which looks like this:

import React from 'react';
import { router } from 'kea-router'
import { useValues } from 'kea';

export default function NavLink(props = {}) {

    let { location: { pathname } } = useValues(router);

    pathname = pathname.toLowerCase();
    const isActive = props.href.toLowerCase() === pathname ||
        (!props.exact &&
            pathname.startsWith(props.href) &&
            pathname.charAt(props.href.length) === "/");

    let clsName = (props.className || '');
    if (isActive) {
        clsName += " active";
    }

    return <a
        {...props}
        onClick={(event) => {
            if (!props.target) {
                event.preventDefault()
                router.actions.push(props.href) // router is mounted automatically, so this is safe to call
            }
            props.onClick && props.onClick(event)
        }}
        className={clsName}
    />

}

There's an additional exact to allow matching the exact pathname. Looks good?

I'll send a PR next later this week.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants