Note: Dash.NET is currently considered experimental. If your organization is interested in sponsoring Dash.NET, please get in touch.

Basic Dash Callbacks

This is the 2nd chapter of the Dash Fundamentals. The previous chapter covered the Dash app layout and the next chapter covers interactive graphing. Just getting started? Make sure to install the necessary dependencies.

In the previous chapter we learned that app.withLayout describes what the app looks like and is a hierarchical tree of components. The Dash.NET.Html module provides classes for all of the HTML tags, and the keyword arguments describe the HTML attributes like style, className, and id. The Dash.NET.DCC module generates higher-level components like controls and graphs.

This chapter describes how to make your Dash apps using callback functions: functions that are automatically called by Dash whenever an input component's property changes, in order to update some property in another component (the output).

For optimum user-interaction and chart loading performance, production Dash apps should consider the Job Queue, HPC, Datashader, and horizontal scaling capabilities of Dash Enterprise.

Let's get started with a simple example of an interactive Dash app.

Simple Interactive Dash App

If you're using Dash Enterprise's Data Science Workspaces, copy & paste the below code into your Workspace (see video).

Find out if your company is using Dash Enterprise

open Dash.NET

let dslLayout = 
    Html.div [
        Attr.children [
            Html.h6 [ 
                Attr.children "Change the value in the text box to see callbacks in action!" 
            ]
            Html.div [
                Attr.children [
                    Html.text "Input: "
                    Input.input "my-input" [
                        Input.Attr.value "initial value"
                        Input.Attr.inputType ComponentPropTypes.Text
                    ]
                ]
            ]
            Html.br []
            Html.div [
                Attr.id "my-output"
            ]
        ]
    ]

let updateOutputDivCallback =
    Callback.singleOut (
        "my-input" @. Value,
        "my-output" @. Children,
        fun (inputValue:string) -> 
            "my-output" @. Children => sprintf "Output: %s" inputValue
        , PreventInitialCall = false
    )

[<EntryPoint>]
let main args =
    DashApp.initDefault()
    |> DashApp.withLayout dslLayout
    |> DashApp.addCallback updateOutputDivCallback
    |> DashApp.run args

Let's break down this example:

  1. The "inputs" and "outputs" of our application are described as the arguments of the Callback.singleOut or Callback.multiOut functions.
  1. In Dash, the inputs and outputs of our application are simply the properties of a particular component. In this example, our input is the "value" property of the component that has the ID "my-input". Our output is the "children" property of the component with the ID "my-output".
  2. Whenever an input property changes, the function that the callback decorator wraps will get called automatically. Dash provides this callback function with the new value of the input property as its argument, and Dash updates the property of the output component with whatever was returned by the function.
  3. The component_id and component_property keywords are optional (there are only two arguments for each of those objects). They are included in this example for clarity but will be omitted in the rest of the documentation for the sake of brevity and readability.
  4. Don't confuse the CallbackInput object and the DCC.Input.input object. The former is just used in these callback definitions and the latter is an actual component.
  5. Notice how we don't set a value for the children property of the my-output component in the layout. When the Dash app starts, it automatically calls all of the callbacks with the initial values of the input components in order to populate the initial state of the output components. In this example, if you specified the div component as Html.div(id='my-output', children='Hello world'), it would get overwritten when the app starts.

It's sort of like programming with Microsoft Excel: whenever a cell changes (the input), all the cells that depend on that cell (the outputs) will get updated automatically. This is called "Reactive Programming" because the outputs react to changes in the inputs automatically.

Remember how every component is described entirely through its set of keyword arguments? Those arguments that we set in F# become properties of the component, and these properties are important now. With Dash's interactivity, we can dynamically update any of those properties using callbacks. Often we'll update the children property of HTML components to display new text (remember that children is responsible for the contents of a component) or the figure property of a DCC.Graph.graph component to display new data. We could also update the style of a component or even the available options of a DCC.Dropdown.dropdown component!


Let's take a look at another example where a DCC.Slider.slider updates a DCC.Graph.graph.

Dash App Layout With Figure and Slider

open Dash.NET
open Plotly.NET
open FSharp.Data

let df = CsvFile.Load("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv").Rows |> List.ofSeq

let dslLayout = 
    Html.div [
        Attr.children [
            Graph.graph "graph-with-slider" []
            Slider.slider "year-slider" [
                Slider.Attr.min (df |> List.map (fun r -> r.Item "year" |> int) |> List.min)
                Slider.Attr.max (df |> List.map (fun r -> r.Item "year" |> int) |> List.max)
                Slider.Attr.value (df |> List.map (fun r -> r.Item "year" |> int) |> List.min)
                Slider.Attr.marks (
                    df 
                    |> List.map (fun r -> r.Item "year") 
                    |> List.distinct 
                    |> List.map (fun y -> (y, Slider.MarkValue.String y))
                    |> Map.ofList
                    |> Slider.MarksType
               )
            ]
        ]
    ]

let updateFigureCallback =
    Callback.singleOut (
        "year-slider" @. Value,
        "graph-with-slider" @. (CustomProperty "figure"),
        fun (inputValue:string) -> 
            let inputYear = inputValue |> int
            let filteredDf = df |> List.filter (fun r -> r.Item "year" |> int = inputYear)

            let xData = filteredDf |> List.map (fun r -> r.Item "gdpPercap")
            let yData = filteredDf |> List.map (fun r -> r.Item "lifeExp")
            let sizeLabels = filteredDf |> List.map (fun r -> r.Item "pop")
            let sizeData = sizeLabels |> List.map (fun s -> (double s / 10000000.))
            let countryData = filteredDf |> List.map (fun r -> r.Item "country")
            let contData = filteredDf |> List.map (fun r -> r.Item "continent")

            let labels = 
                List.zip3 countryData contData sizeLabels
                |> List.map (fun (cty, cnt, sz) -> sprintf "%s, %s, Population %s" cty cnt sz)

            let fig = 
                Chart.Bubble(
                    xData, 
                    yData, 
                    sizeData,
                    Showlegend = true,
                    Labels = labels
                )
                |> Chart.withX_Axis(
                    Axis.LinearAxis.init(
                        AxisType = StyleParam.AxisType.Log,
                        Title = "GDP Per Capita"
                    )
                )
                |> Chart.withY_Axis(
                    Axis.LinearAxis.init(
                        Title = "Life Expectancy"
                    )
                )
                |> GenericChart.toFigure

            "graph-with-slider" @. (CustomProperty "figure") => fig
    )

[<EntryPoint>]
let main args =
    DashApp.initDefault()
    |> DashApp.withLayout dslLayout
    |> DashApp.addCallback updateFigureCallback
    |> DashApp.run args

Theming with Dash Enterprise Design Kit

Default Theme Default Theme

Mars Theme Mars Theme

Neptune Theme Neptune Theme

Miller Theme Miller Theme

Extrasolar Theme Extrasolar Theme

Preset Themes Preset Themes

In this example, the "value" property of the DCC.Slider.slider is the input of the app, and the output of the app is the "figure" property of the DCC.Graph.graph. Whenever the value of the DCC.Slider.slider changes, Dash calls the callback function update_figure with the new value. The function filters the dataframe with this new value, constructs a figure object, and returns it to the Dash application.

There are a few nice patterns in this example:

  1. We use the FSharp.Data library to load our dataframe at the start of the app: let df = CsvFile.Load(...).Rows |> List.ofSeq. This dataframe df is in the global state of the app and can be read inside the callback functions.
  2. Loading data into memory can be expensive. By loading querying data at the start of the app instead of inside the callback functions, we ensure that this operation is only done once -- when the app server starts. When a user visits the app or interacts with the app, that data (df) is already in memory. If possible, expensive initialization (like downloading or querying data) should be done in the global scope of the app instead of within the callback functions.
  3. The callback does not modify the original data, it only creates copies of the dataframe by filtering . This is important: your callbacks should never modify variables outside of their scope. If your callbacks modify global state, then one user's session might affect the next user's session and when the app is deployed on multiple processes or threads, those modifications will not be shared across sessions.
  4. We are turning on transitions with layout.transition to give an idea of how the dataset evolves with time: transitions allow the chart to update from one state to the next smoothly, as if it were animated.

Sign up for Dash Club → Two free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.

Dash App With Multiple Inputs

In Dash, any "output" can have multiple "input" components. Here's a simple example that binds five inputs (the value property of two DCC.Dropdown.dropdown components, two DCC.Radioitems.radioitems components, and one DCC.Slider.slider component) to one output component (the figure property of the DCC.Graph.graph component).

open Dash.NET
open Feliz
open FSharp.Data
open Plotly.NET

let df = CsvFile.Load("https://plotly.github.io/datasets/country_indicators.csv").Rows |> List.ofSeq
let available_indicators = df |> List.map (fun r -> r.Item "Indicator Name") |> List.distinct

let dslLayout = 
    Html.div [
        Attr.children [
            Html.div [
                Attr.children [
                    Dropdown.dropdown "xaxis-column" [ 
                        Dropdown.Attr.options (available_indicators |> List.map (fun i -> {Label = i; Value = i; Disabled = false; Title = i}))
                        Dropdown.Attr.value "Fertility rate, total (births per woman)"
                    ]
                    RadioItems.radioItems "xaxis-type" [
                        RadioItems.Attr.options (["Linear"; "Log"] |> List.map (fun i -> {Label = i; Value = i; Disabled = false}))
                        RadioItems.Attr.value "Linear"
                        RadioItems.Attr.labelStyle [Css.displayInlineBlock]
                    ]
                ]
                Attr.style [Css.width (length.perc 48); Css.displayInlineBlock]
            ]
            Html.div [
                Attr.children [
                    Dropdown.dropdown "yaxis-column" [ 
                        Dropdown.Attr.options (available_indicators |> List.map (fun i -> {Label = i; Value = i; Disabled = false; Title = i}))
                        Dropdown.Attr.value "Life expectancy at birth, total (years)"
                    ]
                    RadioItems.radioItems "yaxis-type" [
                        RadioItems.Attr.options (["Linear"; "Log"] |> List.map (fun i -> {Label = i; Value = i; Disabled = false}))
                        RadioItems.Attr.value "Linear"
                        RadioItems.Attr.labelStyle [Css.displayInlineBlock]
                    ]
                ]
                Attr.style [Css.width (length.perc 48); Css.floatRight; Css.displayInlineBlock]
            ]
            Graph.graph "indicator-graphic" []
            Slider.slider "year-slider" [
                Slider.Attr.min (df |> List.map (fun r -> r.Item "Year" |> int) |> List.min)
                Slider.Attr.max (df |> List.map (fun r -> r.Item "Year" |> int) |> List.max)
                Slider.Attr.value (df |> List.map (fun r -> r.Item "Year" |> int) |> List.min)
                Slider.Attr.marks (
                    df 
                    |> List.map (fun r -> r.Item "Year") 
                    |> List.distinct 
                    |> List.map (fun y -> (y, Slider.MarkValue.String y))
                    |> Map.ofList
                    |> Slider.MarksType
               )
            ]
        ]
    ]

let updateFigureCallback =
    Callback.singleOut (
        [ "xaxis-column" @. Value
          "yaxis-column" @. Value
          "xaxis-type" @. Value
          "yaxis-type" @. Value
          "year-slider" @. Value ],
        "indicator-graphic" @. (CustomProperty "figure"),
        fun xaxisColumnName yaxisColumnName xaxisType yaxisType yearValue -> 
            let filteredDf = df |> List.filter (fun r -> r.Item "Year" = yearValue)

            let xData = filteredDf |> List.filter (fun r -> r.Item "Indicator Name" = xaxisColumnName) |> List.map (fun r -> r.Item "Value")
            let yData = filteredDf |> List.filter (fun r -> r.Item "Indicator Name" = yaxisColumnName) |> List.map (fun r -> r.Item "Value")
            let countryData = filteredDf |> List.map (fun r -> r.Item "Country Name")

            let fig = 
                Chart.Scatter(
                    xData, 
                    yData,
                    StyleParam.Mode.Markers,
                    Showlegend = true,
                    Labels = countryData
                )
                |> Chart.withX_Axis(
                    Axis.LinearAxis.init(
                        AxisType = (if xaxisType = "Linear" then StyleParam.AxisType.Linear else StyleParam.AxisType.Log),
                        Title = xaxisColumnName
                    )
                )
                |> Chart.withY_Axis(
                    Axis.LinearAxis.init(
                        AxisType = (if yaxisType = "Linear" then StyleParam.AxisType.Linear else StyleParam.AxisType.Log),
                        Title = yaxisColumnName
                    )
                )
                |> GenericChart.toFigure

            "indicator-graphic" @. (CustomProperty "figure") => fig
        , PreventInitialCall = false
    )

[<EntryPoint>]
let main args =
    DashApp.initDefault()
    |> DashApp.withLayout dslLayout
    |> DashApp.addCallback updateFigureCallback
    |> DashApp.run args

Theming with Dash Enterprise Design Kit

Default Theme Default Theme

Mars Theme Mars Theme

Neptune Theme Neptune Theme

Miller Theme Miller Theme

Extrasolar Theme Extrasolar Theme

Design Kit Theme Editor Design Kit Theme Editor

In this example, the callback executes whenever the value property of any of the DCC.Dropdown.dropdown, DCC.Slider.slider, or DCC.Radioitems.radioitems components change.

The input arguments of the callback are the current value of each of the "input" properties, in the order that they were specified.

Even though only a single Input changes at a time (i.e. a user can only change the value of a single Dropdown in a given moment), Dash collects the current state of all the specified Input properties and passes them into the callback function. These callback functions are always guaranteed to receive the updated state of the app.

Let's extend our example to include multiple outputs.

Dash App With Multiple Outputs

So far all the callbacks we've written only update a single Output property. We can also update several outputs at once: list all the properties you want to update in Callback.multiOut, and return that many items from the callback. This is particularly useful if two outputs depend on the same computationally intensive intermediate result, such as a slow database query.

open Dash.NET
open System

let dslLayout = 
    Html.div [
        Attr.children [
            Input.input "num-multi" [
                Input.Attr.inputType ComponentPropTypes.Number
                Input.Attr.value 5
            ]
            Html.table [
                Attr.children [
                    Html.tr [ 
                        Attr.children [
                            Html.td [ Attr.children [ Html.text "x"; Html.sup [ Attr.children 2 ] ] ]
                            Html.td [ Attr.id "square" ]
                        ]
                    ]
                    Html.tr [ 
                        Attr.children [
                            Html.td [ Attr.children [ Html.text "x"; Html.sup [ Attr.children 3 ] ] ]
                            Html.td [ Attr.id "cube" ]
                        ]
                    ]
                    Html.tr [ 
                        Attr.children [
                            Html.td [ Attr.children [ Html.text 2; Html.sup [ Attr.children "x" ] ] ]
                            Html.td [ Attr.id "twos" ]
                        ]
                    ]
                    Html.tr [ 
                        Attr.children [
                            Html.td [ Attr.children [ Html.text 3; Html.sup [ Attr.children "x" ] ] ]
                            Html.td [ Attr.id "threes" ]
                        ]
                    ]
                    Html.tr [ 
                        Attr.children [
                            Html.td [ Attr.children [ Html.text "x"; Html.sup [ Attr.children "x" ] ] ]
                            Html.td [ Attr.id "x^x" ]
                        ]
                    ]
                ]
            ]
        ]
    ]

let updateOutputTableCallback =
    Callback.multiOut (
        "num-multi" @. Value,
        [ "square" @. Children 
          "cube" @. Children
          "twos" @. Children
          "threes" @. Children
          "x^x" @. Children ],
        fun (inputValue: string) ->
            match Double.TryParse inputValue with
            | true, value -> 
                [ "square" @. Children => value ** 2.
                  "cube" @. Children => value ** 3.
                  "twos" @. Children => 2. ** value
                  "threes" @. Children => 3. ** value
                  "x^x" @. Children => value ** value ]
            | _ -> []
        , PreventInitialCall = false
    )

[<EntryPoint>]
let main args =
    DashApp.initDefault()
    |> DashApp.withLayout dslLayout
    |> DashApp.addCallback updateOutputTableCallback
    |> DashApp.run args

A word of caution: it's not always a good idea to combine outputs, even if you can:

  • If the outputs depend on some, but not all, of the same inputs, then keeping them separate can avoid unnecessary updates.
  • If the outputs have the same inputs but they perform very different computations with these inputs, keeping the callbacks separate can allow them to run in parallel.

Dash App With Chained Callbacks

You can also chain outputs and inputs together: the output of one callback function could be the input of another callback function.

This pattern can be used to create dynamic UIs where, for example, one input component updates the available options of another input component. Here's a simple example.

open Dash.NET

type Country =
    { Name: string 
      Cities: string list }

let countries =
    [ { Name = "America"; Cities = ["New York City"; "San Francisco"; "Cincinnati"]}
      { Name = "Canada"; Cities = ["Montreal"; "Toronto"; "Ottawa"]} ]

let dslLayout = 
    Html.div [
        Attr.children [
            RadioItems.radioItems "countries-radio" [
                RadioItems.Attr.options (countries |> List.map (fun c -> {Label = c.Name; Value = c.Name; Disabled = false}))
                RadioItems.Attr.value "America"
            ]
            Html.hr []
            RadioItems.radioItems "cities-radio" []
            Html.hr []
            Html.div [Attr.id "display-selected-values"]
        ]
    ]

let setCitiesOptions =
    Callback.singleOut (
        "countries-radio" @. Value,
        "cities-radio" @. (CustomProperty "options"),
        fun (selectedCountry: string) -> 
            "cities-radio" @. (CustomProperty "options") => 
                (countries 
                 |> List.tryFind (fun c -> c.Name = selectedCountry)
                 |> Option.map (fun c -> c.Cities)
                 |> Option.map (List.map (fun c -> {|Label = c; Value = c|}))
                 |> Option.defaultValue [])
        , PreventInitialCall = false
    )

let setCitiesValue =
    Callback.singleOut (
        "cities-radio" @. (CustomProperty "options"),
        "cities-radio" @. Value,
        fun (availableOptions: {|Label: string; Value: string|} list) -> 
            "cities-radio" @. Value => availableOptions.[0].Value
        , PreventInitialCall = false
    )

let setDisplayChildren =
    Callback.singleOut (
        [ "countries-radio" @. Value
          "cities-radio" @. Value ],
        "display-selected-values" @. (CustomProperty "children"),
        fun (selectedCountry: string) (selectedCity: string) -> 
            "display-selected-values" @. (CustomProperty "children") => sprintf "%s is a city in %s" selectedCity selectedCountry
        , PreventInitialCall = false
    )

[<EntryPoint>]
let main args =
    DashApp.initDefault()
    |> DashApp.withLayout dslLayout
    |> DashApp.addCallback setCitiesOptions
    |> DashApp.addCallback setCitiesValue
    |> DashApp.addCallback setDisplayChildren
    |> DashApp.run args

The first callback updates the available options in the second DCC.Radioitems.radioitems component based off of the selected value in the first DCC.Radioitems.radioitems component.

The second callback sets an initial value when the options property changes: it sets it to the first value in that options array.

The final callback displays the selected value of each component. If you change the value of the countries DCC.Radioitems.radioitems component, Dash will wait until the value of the cities component is updated before calling the final callback. This prevents your callbacks from being called with inconsistent state like with "America" and "Montréal".

Dash App With State

In some cases, you might have a "form"-like pattern in your application. In such a situation, you may want to read the value of an input component, but only when the user is finished entering all of their information in the form rather than immediately after it changes.

Attaching a callback to the input values directly can look like this:

open Dash.NET

let dslLayout = 
    Html.div [
        Attr.children [
            Input.input "input-1" [ 
                Input.Attr.inputType InputType.Text
                Input.Attr.value "Montreal" 
            ]
            Input.input "input-2" [ 
                Input.Attr.inputType InputType.Text
                Input.Attr.value "Canada" 
            ]
            Html.div [Attr.id "output-state"]
        ]
    ]

let setOutputDivValue =
    Callback.singleOut (
        [ "input-1" @. Value
          "input-2" @. Value ],
        "output-state" @. (CustomProperty "children"),
        fun input1 input2 -> 
            "output-state" @. (CustomProperty "children") 
                => sprintf "Input 1 is %s, Input 2 is %s" input1 input2
        , PreventInitialCall = false
    )

[<EntryPoint>]
let main args =
    DashApp.initDefault()
    |> DashApp.withLayout dslLayout
    |> DashApp.addCallback setOutputDivValue
    |> DashApp.run args

In this example, the callback function is fired whenever any of the attributes described by the Input change. Try it for yourself by entering data in the inputs above.

State allows you to pass along extra values without firing the callbacks. Here's the same example as above but with the two DCC.Input.input components as State and a new button component as an Input.

open Dash.NET

let dslLayout = 
    Html.div [
        Attr.children [
            Input.input "input-1-state" [ 
                Input.Attr.inputType InputType.Text
                Input.Attr.value "Montreal" 
            ]
            Input.input "input-2-state" [ 
                Input.Attr.inputType InputType.Text
                Input.Attr.value "Canada" 
            ]
            Html.button [
                Attr.id "submit-button-state"
                Attr.n_clicks 0
                Attr.children "Submit"
            ]
            Html.div [Attr.id "output-state"]
        ]
    ]

let setOutputDivValue =
    Callback.singleOut (
        "submit-button-state" @. (CustomProperty "n_clicks"),
        "output-state" @. (CustomProperty "children"),
        fun nClicks input1 input2 -> 
            "output-state" @. (CustomProperty "children") 
                => sprintf "The button has been pressed %s times, Input 1 is %s, Input 2 is %s" nClicks input1 input2
        , State = 
            [ CallbackState.create("input-1-state", "value")
              CallbackState.create("input-2-state", "value") ]
        , PreventInitialCall = false
    )

[<EntryPoint>]
let main args =
    DashApp.initDefault()
    |> DashApp.withLayout dslLayout
    |> DashApp.addCallback setOutputDivValue
    |> DashApp.run args

In this example, changing text in the DCC.Input.input boxes won't fire the callback, but clicking on the button will. The current values of the DCC.Input.input values are still passed into the callback even though they don't trigger the callback function itself.

Note that we're triggering the callback by listening to the n_clicks property of the Html.button component. n_clicks is a property that gets incremented every time the component has been clicked on. It's available in every component in the Dash.NET.Html module, but most useful with buttons.

Summary

We've covered the fundamentals of callbacks in Dash. Dash apps are built off of a set of simple but powerful principles: UIs that are customizable through reactive callbacks. Every attribute/property of a component can be modified as the output of a callback, while a subset of the attributes (such as the value property of DCC.Dropdown.dropdown component) are editable by the user through interacting with the page.


The next part of the Dash Fundamentals covers interactive graphing. Dash Fundamentals Part 3: Interactive Graphing