Callback to change only one element of style dict


Let’s say I have a style dict of an html.Div that looks like this:

        style = {
            "position": "absolute",
            "backgroundColor": "#FFFFFF",
            "height": "35vh",
            "width": "500px",
            "border": "1px solid",
            "borderRadius": "5px",
            "boxShadow": "0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)",
            "display": "none",

If the output of a callback should only change the value of one of these parameters (e.g. width to 600px) but everything else should remain unchanged, is there a way for me to avoid messy code where the callback output contains the entire dictionary again?

Hi @domingo ,

I would do it like this:

    input_dict.update({'width': '600px'})
    return input_dict

but I guess this is what you mean by “messy” code.


Hi @domingo

You can include the style as a State in the callback, then update it like any dict - for example:

    Output("my_div", "style"),
    Input("button", "n_clicks"),
    State("my_div", "style")
def update(n, style):
    style["backgroundColor"] = "red"
    return style
1 Like

Thanks for your feedback @AIMPED and @AnnMarieW. Both solutions seem to work, I have marked @AnnMarieW’s solution as the correct one as it seems more “dashy” to me. Appreciate the swift feedback.

Haha @AIMPED beat me to it :racing_car:

1 Like