-
I have this code for handling the active class (menu-selected). My problem is that I need two clicks to make it work. Why? use dioxus::prelude::*;
use crate::router::Route;
#[component]
pub fn Menu() -> Element {
const HOME: &str = manganis::mg!(file("./assets/img/home.svg"));
const ABOUT: &str = manganis::mg!(file("./assets/img/about.svg"));
let mut selected = use_signal(|| "home");
rsx! {
div {
class: "menu",
div {
class: format!("{}", if *selected.read() == "home" { "menu-selected" } else { "" }),
onclick: move |_| selected.set("home"),
Link {
to: Route::Home {},
div {
img { src: HOME }
}
div {
"Home"
}
}
}
div {
class: format!("{}", if *selected.read() == "about" { "menu-selected" } else { "" }),
onclick: move |_| selected.set("about"),
Link {
to: Route::About {},
div {
img { src: ABOUT }
}
div {
"About"
}
}
}
}
}
} |
Beta Was this translation helpful? Give feedback.
Answered by
ghost
Nov 16, 2024
Replies: 2 comments
-
I have solved it by getting the current path and set as default value for |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected
-
You can also use a signal to set its value when clicking a link by attaching an use dioxus::prelude::*;
#[derive(PartialEq, Clone)]
enum NavLink {
HomePage,
Features,
Roadmap,
Faq,
Testimonial,
Team,
Blog,
}
#[component]
pub fn NavLinks() -> Element {
let mut active_link = use_signal(|| NavLink::HomePage);
let is_active = |link: &NavLink| {
if active_link() == *link {
"active-underline"
} else {
""
}
};
let nav_links = vec![
(NavLink::HomePage, "#home", "Home"),
(NavLink::Features, "#features", "Features"),
(NavLink::Roadmap, "#roadmap", "Roadmap"),
(NavLink::Faq, "#faq", "Faq"),
(NavLink::Testimonial, "#testimonial", "Testimonial"),
(NavLink::Team, "#team", "Team"),
(NavLink::Blog, "#blog", "Blog"),
];
rsx! {
div { class: "flex flex-col md:flex-row gap-4 md:gap-8",
for (link, href, label) in nav_links {
Link {
to: href,
class: format!("text-black text-lg hover:decoration-gray-500 {}", is_active(&link)),
onclick: move |_| active_link.set(link.clone()),
"{label}"
}
}
}
}
} Example taken from |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have solved it by getting the current path and set as default value for
selected
signal.