Grasia / grasia-dash-components

Extending Plotly's Dash component suite for @Grasia.
MIT License
18 stars 0 forks source link

Dynamically created Tabs #2

Closed alastairbegley closed 6 years ago

alastairbegley commented 6 years ago

Tabs don't show if they are dynamically created. This code works with the dcc tabs component.

import dash
import dash_core_components as dcc
import dash_html_components as html
import grasia_dash_components as gdc
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate

app = dash.Dash()

app.config['suppress_callback_exceptions']=True

app.layout = html.Div(
    [
        html.H1(children='Tabs'),
        html.Div([
            dcc.Input(
                id='location-text',
                placeholder='Enter location',
                value='',
                type='text',
                className='form-control col-lg-4 col-md-6 col-sm-8 col-9'
            ),
            html.Div(
                html.Button(
                    'Submit',
                    id='search-button',
                    className='btn btn-outline-primary',
                    type='Submit'
                ),
                className='col-lg-2 col-md-2 col-sm-2 col-2'
            )
        ]),
        html.Div(
            id='tabDiv'
        )
    ],
    className="container"
)

@app.callback(
    Output('tabDiv', 'children'),
    [
        Input('search-button', 'n_clicks')
    ],
    [
        State('tabDiv', 'children'),
    ]
)
def get_tabs(n_clicks, tabs):
    if n_clicks < 1:
        return []
    if tabs == [] or tabs is None:
        return [
            gdc.Tabs(
                tabs=[
                    {'label': 'Plot vs Height ', 'value': 'height'},
                    {'label': 'Plot vs Time ', 'value': 'time'},
                ],
                value='height',
                id='tabs'
            ),
            html.Div(id='tab-output')
        ]
    raise PreventUpdate('Tabs already exist')

@app.callback(
    Output('tab-output', 'children'),
    [
        Input('tabs', 'value')
    ]
)
def populate_graph(tab):
    if tab == 'height':
        return html.P("Height")
    if tab == 'time':
        return html.P("Time")

if __name__ == '__main__':
    app.run_server(debug=True)
Akronix commented 6 years ago

Apparently, Dash only load the react components that are statically added to app.layout. To workaround this, I've added an Import component in grasia-dash-components@0.1.1, which it's an empty component, but adding it to the layout forces Dash to load gdc. You can see your "example" up and running here: https://test-grasia-dash-components.herokuapp.com/ and its source code here.

alastairbegley commented 6 years ago

That seems to do the trick, thanks

Akronix commented 6 years ago

related: https://github.com/plotly/dash-renderer/issues/46