Close OffCanvas menu when clicking on NavItem

Hi All,

I have added a OffCanvas Bootstrap component in my dash app to handle my navigation on mobile - the code currently is straightforward and looks like this:

dbc.Col(
                                dbc.Offcanvas(
                                    dbc.Nav(
                                        [
                                            dbc.NavItem(
                                                dbc.NavLink("Testing",
                                                href="/testing"
                                                )
                                            ),
                                        ]
                                    ),
                                    id="navbar-collapse",
                                    is_open=False,
                                    title="Navigation",
                                ),id="dropdown"
                            ),

Currently now when I click on the testing link it successfully navigates me to the /Testing page, however, the OffCanvas stays open - how can I go about when clicking on the NavLink it closes the Offcanvas?

Hi @DrSmith69

This could be handled using a callback, the dbc.navlink component has a n_clicks property just like a button. Just add it as an input to your existing callback which toggles the Offcanvas.

@app.callback(
    Output("offcanvas", "is_open"),
    Input("your-button-id", "n_clicks"),
    Input("navlink_id", "n_clicks"),     #additional input from your navlink
    [State("offcanvas", "is_open")],
)
def toggle_offcanvas(n1, n2, is_open):
    if n1 or n2:
        return not is_open
    return is_open
2 Likes

Legend! Thank you - was as simple as that, added an id to my navlink and included that in the default callback just as you have shown above, works like a charm!

2 Likes

Hi @atharvakatre,

Thanks for your suggestion - it works well when there is one navlink present.

When we’re using dash pages, we use a list comprehension to generate a list of links. How can we get unique IDs for each page in this case?

What if you give the entire dcc.Link node an id then no matter where it is clicked on within that div it will react the same?