Black Lives Matter. Please consider donating to Black Girls Code today.

How to init fields in Dash app properly in multi page app

Hi I have a multi page app that imports all the layouts in the front page and depending on the path it would return the layout, so on initialization it will try to initialize all the initialization on all the pages, even the ones I don’t play on opening.

Is there a best practice so that it will only initialize a page when you land on the page and not when you are on the index page?

If you assign app.layout to a function (without evaluating it), it will be evaluated on each initial page load. Then in your location callback function you can dynamically evaluate only the page layout it is about to load.

Edit: now that I think about it a little more, using a function as a the app.layout is not really relevant. The main thing is that you don’t want page-specific layout fragments in other modules to be evaluated on init. You can solve this simply by wrapping up the code that creates the layout instance (eg a top level html.Div) in a function that returns it. Then, in your router callback, when returning the layout for the page you want, just evaluate the function and return the result.