Get 2025 Templates Mega Bundle!$1000 worth of 19 Bootstrap HTML, Vue & React Templates + 3 Vector Sets for just $99
Get for 99$

Dropdown Menu close on link click


When I click a link on the nav item's dropdown menu, the menu stays open as the page navigates (since the header stays the same and only the content is changed via React and React Router). Is it possible to close the menu after link click?


Text formatting options
Submit

Replies (6)


Yes, you can close the dropdown menu by using a state variable to manage its visibility. On the "View all" button click, set the state to close the menu. In Metronic React, you can use the setState method to handle this. Here's a basic example:

jsx
Copy code
const [isOpen, setIsOpen] = useState(false);

const handleViewAllClick = () => {
// Handle the view all action
setIsOpen(false); // Close the dropdown
};

// In your dropdown component
<button onClick={handleViewAllClick}>View all</button>
<Dropdown isOpen={isOpen} toggle={() => setIsOpen(!isOpen)}>{/* Dropdown content */}</Dropdown>
This way, clicking the "View all" button will close the dropdown.

You can read more about it here - https://geekydane.com



Hi,

This is done on purpose since the currently activated nav menu should be open and the currently open link must be activated.

If you want to hide menu items when you change the page you can call hideAccordions function for menu instance.


menu?.hideAccordions(menuItem);


Regards,
Lauris Stepanovs,
Keenthemes Support Team



Where would you add this function?



Hi,

Thank you for returning back to us.

You can do this inside menu component, get menu instance, and then for your menu instance you can call hideAccordions function.

Regards,
Lauris Stepanovs,
Keenthemes Support Team



Err... sorry, how do I get the menu instance to call the hideAccordions function for?



Hi,

Sorry for the delay with the reply.

We checked and hideAccordions will not work due to our components initialization timeout.

I think the easiest way for you to achieve menu accordion hide is just by removing 'hover', 'show', and 'active' classes from menu accordion class list.

Here is an example:

const menu = useRef<HTMLDivElement>(null);
const location = useLocation();

useEffect(()=>{
const showItems = menu.current?.querySelectorAll("div.show");
const hoverItems = menu.current?.querySelectorAll("div.hover");
const activeItems = menu.current?.querySelectorAll("div.acive");

showItems?.forEach((item)=>{
item.classList.remove("show");
})

hoverItems?.forEach((item)=>{
item.classList.remove("hover");
})

activeItems?.forEach((item)=>{
item.classList.remove("acive");
})
}, [location]);


Don't forget to add ref={menu} attribute on your menu element.

Regards,
Lauris Stepanovs,
Keenthemes Support Team


Text formatting options
Submit
Text formatting options
Submit