Centering checklist

Hello Dash Community,

I am working on project and the requirement is that users should be able to upload Excel file, select columns that they want and then display data table. I am running issue with displaying columns names’ checklist. How can we make checklist horizontal instead of vertical? Any help would be much appreciated! Go Dash!

import base64
import datetime
import io
import dash
import numpy as np
import visdcc
import pandas as pd
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
import dash_table as dt
from dash.dependencies import Input, Output, State
from os import listdir
from os.path import isfile, join

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__,
                external_stylesheets=external_stylesheets,
                )

app.layout = html.Div(children=[

    # Header
    dbc.Row(children=[
        html.H3(children=["NLP Parametrized Keywords Search"],
                style={"text-align": "center"})
    ]),

    # Upload
    dcc.Upload(
        id='upload_area',
        children=html.Div([
            html.A('Drag and Drop or Select File')
        ]),
        style={
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '5px',
            'textAlign': 'center',
            'margin': '10px'
        },
        # Don't Allow multiple files to be uploaded
        multiple=False
    ),

    # Checklist
    dbc.Row(children=[

        dbc.Row(children=[
            dbc.Badge("Select Columns:", color="info", className="mr-1")],
            style={'font-weight': 'bold'}),

        dbc.Row(children=[
            dcc.Checklist(
                id="checklist",
            )
        ])
    ],
        style={'width': '100%', 'padding': '5px 5px', 'display': 'inline-block'}
    ),

    # textarea
    dbc.Row(children=[

        dbc.Row(children=[dbc.Badge("Paste Parameters:", color="info", className="mr-1")],
                style={'font-weight': 'bold'}),

        dbc.Row(children=[dcc.Textarea(
            id='textarea',
            value='Enter your Parameters that you want to search...',
            style={'width': '99%', 'height': 100, "text-align": "left"}),
        ]),

        dbc.Row(children=[
            html.Button('Confirm', id='button', n_clicks=0),
        ])
    ],
        style={'width': '100%', 'padding': '5px 5px', 'display': 'inline-block'}
    ),

    dbc.Row(children=[
        html.Div(id='output_children')
    ],
        style={'width': '100%', 'padding': '5px 5px', 'display': 'inline-block'}),

])


# Updating columns check list
@app.callback([Output(component_id='checklist', component_property='options')],
              [Input(component_id='upload_area', component_property='contents'),
               State(component_id='upload_area', component_property='filename'),
               State(component_id='upload_area', component_property='last_modified')],
              prevent_initial_call=True)
def update_output(contents, filename, date):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            # Assume that the user uploaded a CSV file
            dff = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # Assume that the user uploaded an excel file
            dff = pd.read_excel(io.BytesIO(decoded))
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    checklist_options = [{"label": item.title(), "value": item} for item in dff.columns.to_list()]

    return [checklist_options]


# Updating data table
@app.callback(
    [Output(component_id='output_children', component_property='children')],
    [Input(component_id="button", component_property="n_clicks"),
     State(component_id='upload_area', component_property='contents'),
     State(component_id='upload_area', component_property='filename'),
     State(component_id='upload_area', component_property='last_modified'),
     State(component_id='textarea', component_property='value'),
     State(component_id='checklist', component_property='value')],
    prevent_initial_call=True
)
def update_data_table(button, contents, filename, date, textarea, checklist):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            # Assume that the user uploaded a CSV file
            dff = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # Assume that the user uploaded an excel file
            dff = pd.read_excel(io.BytesIO(decoded))
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    # text ready for running NLP backend
    text = textarea

    # checklist filter
    dff = dff[dff.columns[dff.columns.isin(values=checklist)]]

    # data table
    my_children = [
        # File Name Header
        html.H6(children=[f"{filename}"],
                style={"text-align": "center"}),

        # Data Table
        html.Div(children=[dt.DataTable(id="data_table",
                                        columns=[{'id': c, 'name': c} for c in dff.columns],
                                        data=dff.to_dict('records'),
                                        style_cell={
                                            'overflow': 'hidden',
                                            'textOverflow': 'ellipsis',
                                            'minWidth': '100px', 'width': '150px', 'maxWidth': '180px',
                                        },
                                        tooltip_data=[
                                            {
                                                column: {'value': str(value), 'type': 'markdown'}
                                                for column, value in row.items()
                                            } for row in dff.to_dict('records')
                                        ],
                                        # page_size=15,
                                        filter_action="native",
                                        sort_action="native",
                                        # tooltip_duration=None,
                                        # style_data_conditional=styles,
                                        style_table={'overflowX': 'scroll',
                                                     'overflowY': 'scroll',
                                                     "maxHeight": 300,
                                                     },
                                        export_format="xlsx",
                                        export_headers='display',
                                        )],
                 style={'width': '100%', 'display': 'inline-block'})
    ]

    return [my_children]


if __name__ == '__main__':
    app.run_server(debug=True, port=7775)

Hi @liuzc123
Try including the parameter inline=True. Here is an example from the docs:

inline_checklist = html.Div(
    [
        dbc.Label("Choose a bunch"),
        dbc.Checklist(
            options=[
                {"label": "Option 1", "value": 1},
                {"label": "Option 2", "value": 2},
            ],
            value=[],
            id="checklist-inline-input",
            inline=True,
        ),
    ]
)

image

1 Like

Hello, @AnnMarieW

I am using dash_core_components as version 1.16.0. It seems it doesn’t have parameter, “inline=True”. Which version are u using?


THX

Hey @liuzc123 - Sorry, I didn’t notice that you were using dcc.Checklist – I saw that you were using dash-bootstrap-components so I gave you the dbc.Checklist solution.

If you want to stay with dcc.Checklist here is how you do it:

dcc.Checklist(
    options=[
        {'label': 'New York City', 'value': 'NYC'},
        {'label': 'Montréal', 'value': 'MTL'},
        {'label': 'San Francisco', 'value': 'SF'}
    ],
    value=['NYC', 'MTL'],
    labelStyle={'display': 'inline-block'}
)

Note that in the next release of Dash there will be a new inline prop. But that’s not available yet.

The nice thing about the dash-bootstrap-components dbc.Checklist is that the checkbox has your Bootstrap theme colors applied. (Same goes with RadioButton and Switches etc) You can see a demo in the theme explorer

1 Like

@AnnMarieW , that works! Thanks for your kindly help! :cowboy_hat_face:

Great! Feel free to mark it as a solution :slightly_smiling_face: :heavy_check_mark:

1 Like