React to pathname or href change in dash component

Thanks for mentioning the dbc-nav implementation, i was already using it as a reference. The navigation (dash-bootstrap-components) has the same problem, it won’t update its active navlink when dcc.location changes due to a button click:

@app.callback(
              Output("url", "pathname"),
              Input("testbutton", "n_clicks"),
              State("url", "href"),
              )
def change_active_navitem_via_buttonclick(n_clicks, href):
    if n_clicks and n_clicks > 0:
        return app.config["url_base_pathname"] + "pathname"

It does update if a dcc.link is clicked somewhere in the app.

I now use this callback to force a history entry and trigger an event:

app.clientside_callback(
    """
    function(n_clicks, href) {
        if (n_clicks > 0){
            console.log(n_clicks);
            history.pushState({}, '', "/prefix/pathname4/");
            const ON_CHANGE = '_dashprivate_historychange';
            window.dispatchEvent(new CustomEvent(ON_CHANGE));
        }
    }
    """,
    Output("url", "pathname"),
    Input("testbutton", "n_clicks"),
    State("url", "href"),
)

Then the active navitem gets updated like intended.