Svelte store for updating active state on nav items #307
Replies: 2 comments 3 replies
-
I forgot to add the part I needed to complete the event loop. I needed to add the function setActiveAndToggle(item) {
currentNavItem.set(item);
activeItem = item;
isMenuOpen = false;
} Here is a link to the Svelte Store docs |
Beta Was this translation helpful? Give feedback.
-
Hey @jamestagal, That's a great solution, thanks for sharing!
I was actually doing something similar for a client site recently. I initially tried something similar but had issues with edge case:
I ended up taking a slightly different approach:
<Nav {content} />
export let content;
$: active_link = content?.path;
<a href="/about" class={active_link === "/about" ? "active" : ""}>
About
</a>
a.active {
color: red;
} |
Beta Was this translation helpful? Give feedback.
-
Hi all,
I just wanted to share a solution I figured out last night to an issue I had with active navigation items.
Problem: Nav items were being assigned an active state in the header (nav bar) but not being updated when clicking buttons (to nav items) on the site.
Solution: Svelte store
Process:
Create a Svelte store with the value of the
home
nav item.currentNavItem.js
Then imported the store and subscribe to it passing the
activeItem
.Header.svelte
On a nav item:
In a component where there is a button to one of the nav items, import the store;
Then add a on click event to the button which updates the store to the current nav item.
This solution seems simple enough and worked for me but I wonder whether it is the best way to do it.
If anyone has another implementation please share.
Regards,
Ben
Beta Was this translation helpful? Give feedback.
All reactions