Trigger Callback When URL Path is Updated within Dash 2.5 Multi-Page App

I am using the built in Multi-Page feature use_pages=True which was added in 2.5 I believe. In my application I would like to trigger a callback when a specific page loads. However, since there are multiple entry points to this page (from other pages as well), I would like to trigger a callback when the URL changes to a specific path (e.g., /home). Is there any way to do this with the built-in multi-page feature??

Any suggestions would be greatly appreciated. Thanks in advance!

Hello @ayhan.

You can always include dcc.Location in your layout and trigger your callback with pathname property. Syntax for the input will be same as described in https://dash.plotly.com/urls for Multi-Page Apps without Pages.

2 Likes

I recently went through this exactly issue…

I put on a dcc.location in my app.layout (which is in my index.py), along with my dash.page_container.

I then used that dcc.location on several of the pages, but would have something like this in the callback:

@dash.callback(Output('page1','children'),
                 Input('url','pathname'))
def update_page_1(path):
       if path == '/page1':
               ##do something
       else:
               raise PreventUpdate


Basically, it ignores the callback if the path isn’t correct. I started off using multiple dcc.locations which was a mess, don’t do that.

2 Likes

Also, if you are using dash>=2.9.2, be sure to use dcc.Location(refresh="callback-nav") so it will navigate without refreshing the page. More info here:

Another tip is to put the dcc.Location in the app.layout above the dash.page_container - then the forward/back browser buttons will work.

1 Like

@martin2097 @bgivens33 @AnnMarieW Thank you all for the great help!

I added a dcc.Location at the top of my app.layout and added the refresh='callback-nav' like you recommended. This works great with a callback of the structure @bgivens33 outlined above.

2 Likes