Multi-page App "activate" relative path through callback

I have a Multi-page app (using the new Dash pages feature) and I want to manually/programmatically open a new page in a callback once a dcc.Graph clickEvent has been registered. I have seen solutions that use other Python libraries to open a URL in a new tab, but I want a new page to open in the user’s current tab.

Here is some code where I am envisioning a solution would be:

@callback(
    Output("url", "href"),
    Input("graph", "clickData"),
)
def update_page(clickData):
    if clickData is None:
        raise PreventUpdate

    new_url = "/new/url"

    # TODO: Something here to open new page

Hi @marcus_m

This is a great question! You can find an example of this and other features of Pages in my dash-multi-page-app-demos library. You can find more information on how to navigate to a new page in a callback in Examples #15 and #16.


Navigating to a new page in a callback

Example 15. multi_page_update_url_in_callback/

Example 16. multi_page_update_url_from_figure/

With Dash Pages, the routing callback is under-the-hood, which reduces the amount of boilderplate code you need to write. The best way to navigate is to use components such as the dcc.Link or dbc.Button. When the user clicks on these links, it will navigate to the new page without refreshing the page, making the navigation very fast. And the best part? No callback required! :tada:

This works well when you have predefined links. However, at times, you may want to navigate based on an input field, dropdown, or clicking on a figure etc. In these cases, you should update a link dynamically in a callback. While it’s possible to update the href prop of a dcc.Location in a callback, this is not recommended because it refreshes the page. You can see it in this example:


Don’t do it like this! See this example – and how to fix this when you run #15 multi_page_update_url_in_callback/

update_url_in_callback


In this example, we update the links based on the user clicking on the map. When the user clicks on the links, it navigates to the new page without refresing the page. See #16 multi_page_update_url_from_figure/

fight-status

1 Like

Thanks for your quick response, @AnnMarieW !

Example #16 is close, but I want to go to a new page immediately upon a map click, not upon an additional link click. For example, After clicking on the SEA data point, I want to be taken to /flight-status/SEA/arrivals immediately.

I think this more or less the behavior of the not recommended version of example #15.

Sure, then use the method in example #15. As noted in that example, just be sure that the dcc.Location is in the app.py layout rather than one of the other pages.

1 Like