Modular Web Design using Plotly Dash, a very simple implementation of All-In-One Components

Hey Plotly community! I’m excited to share a project I’ve been working on: dash-basecomponent. If you’ve ever struggled with managing component IDs in Dash, especially as your apps grow, this is for you. Inspired by Dash’s All-in-One Components, but aiming for even greater flexibility, dash-basecomponent lets you encapsulate component definitions and IDs in one place, reducing clutter and improving maintainability. I’ll walk you through how it works, including automatic ID assignment, pattern-matching callbacks, and how it can be used to build reusable component libraries.

Although this is similar to all-in-one components, it is easier to use. You don’t need to define a class for “ids”, but instead you can just refer to the same id of a child component that you would use in its callback, all defined within the class you inherit from html.Div (or whatever actual dash component you want to base off of) and BaseComponent (the class I created) like so:

from dash import Dash, html, callback
from dash_basecomponent import BaseComponent as bc

class Counter(html.Div, bc):
    def __init__(self, **kwargs):
        super().__init__([
            html.Button("Increment", id=self.child_id("button")),
            html.Span("0", id=self.child_id("count"), style={"marginLeft": "10px"}),
        ], **kwargs)
    
    @callback(
        bc.ChildOutput("count", "children"),
        bc.ChildInput("button", "n_clicks"),
        prevent_initial_call=True
    )
    def increment_count(n_clicks):
        return str(n_clicks)

app = Dash(__name__)
app.layout = Counter()

if __name__ == "__main__":
    app.run_server(debug=True)

If you want to learn more about how I did this or how to use the package, check out my blog post :smile: Creating Modular Web Components in Plotly Dash with BaseComponent | CODING w/RICKY

1 Like