React to pathname or href change in dash component

I would like my dash-component to be able to change the navitem/subnavitem which is rendered active if a callback changes the href or pathname of dcc.Location. This doesn’t trigger an event with the _dashprivate_historychange event type (see below).

I created a navigation dash-component which uses _dashprivate_historychange (dash/History.js at dev · plotly/dash · GitHub) to render the activated navitem and subnavitem as active. This works if i click on a _Link.react.js inside the navitem/subnavitem and if i click on a dcc.Link somewhere else on the page.

Do you have any ideas how i would best be able to trigger an _dashprivate_historychange event in a dash callback OR how else i could make my dash-component url-change aware?

The NavLink in dash-bootstrap-components can automatically set the active property based on the current location. You can see the implementation here.

If you want to trigger a callback just use the pathname property of dcc.Location as an input to your callback.

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:

              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 is clicked somewhere in the app.

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

    function(n_clicks, href) {
        if (n_clicks > 0){
            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.

Ah interesting. I think it would make sense if Location dispatched an event when it was changed by a callback. Maybe worth raising an issue on the dash-core-components repo?