# Dash Layout

> This is the 1st chapter of the Dash Fundamentals. The next chapter covers Dash callbacks.

This tutorial will walk you through a fundamental aspect of Dash apps, the app `layout`, through six self-contained apps.

For production Dash apps, we recommend styling the app `layout` with Dash Enterprise Design Kit.

Dash apps are composed of two parts. The first part is the "`layout`", which describes what the app looks like. The second part describes the interactivity of the app and will be covered in the next chapter.

Note: Throughout this documentation,

R code examples are meant to be saved as files and executed either using `source("app.R")` in your R terminal or using `Rscript app.R` in a shell. Throughout this documentation we'll use the former method.

> 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

To get started, create a file named `app.R` , copy the code below into it, and then run it with `source("app.R")`.

    library(dash)
    library(dashCoreComponents)

    # Create a Dash app
    app <- dash_app()

    # Set the layout of the app
    app %>% set_layout(
      h1('Hello Dash'),
      div("Dash: A web application framework for your data."),
      dccGraph(
        figure = list(
          data = list(
            list(
              x = list(1, 2, 3),
              y = list(4, 1, 2),
              type = 'bar',
              name = 'SF'
            ),
            list(
              x = list(1, 2, 3),
              y = list(2, 4, 5),
              type = 'bar',
              name = 'Montr\U{00E9}al'
            )
          ),
          layout = list(title = 'Dash Data Visualization')
        )
      )
    )

    # Run the app
    app %>% run_app()

# Hello Dash

Dash: A web application framework for your data.

    > source("app.R")
    Fire started at 127.0.0.1:8050
    start: 127.0.0.1:8050

Visit http://127.0.0.1:8050/ in your web browser. You should see an app that looks like the one above.

Note:

1. The `layout` is composed of a tree of "components" such as `div` and `dccGraph`.
2. The `dash` package contains an `html` list which has a component for every HTML tag. For convenience, some common HTML tags have shortcuts as functions; e.g. `h1()` and `div()` are aliases for `html$h1()` and `html$div()`. The `h1('Hello Dash')` component generates a `<h1>Hello Dash</h1>` HTML element in your app.

3. Not all components are pure HTML. `DashCoreComponents` contains higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library.

4. Each component is described entirely through the parameters to its function.

5. For pure HTML components, any named argument becomes an attribute on the HTML tag, while any unnamed argument becomes a child. For example, `div(id = "name", "Joe")` results in `<div id="name">Joe</div>`.

6. The fonts in your app will look a little bit different than what is displayed here. This app is using a custom CSS stylesheet and Dash Enterprise Design Kit to modify the default styles of the elements. You can learn more about custom CSS in the CSS tutorial.

### A Quick Note about Syntax

You'll notice that most examples on this website use the pipe operator (`%>%`) to manipulate the Dash app object. The above code can be rewritten to fully embrace the pipe operator as

    dash_app() %>%
      set_layout(...) %>%
      run_app()

or it can be rewritten without the pipe operator as

    app <- dash_app()
    set_layout(app, ...)
    run_app(app)

Functionally there is no difference between these three, so you can choose whichever style best suits you.

### Making Your First Change

You can change the title "Hello Dash" in your app or change the `x` or `y` data. Save the file and restart the app to see your changes.

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.

### More about HTML Components

Any valid HTML tag can be added to a Dash app using the HTML components in the `html` list. For example, a `div` component that results in a `<div>` tag in the app can be created with `html$div()`.

Some common HTML tags, such as `div` and `button`, are also available as functions for your convenience, so you can simply use `div()` or `button()`. Run `?dash::html` to see the full list of HTML tags that support this short form.

An HTML tag can contain arbitrary attributes and content: any named arguments to the function become attributes in the HTML tag, and any unnamed arguments become children. The children can either be simple text or they can be other Dash components themselves.

Let's customize the text in our app by modifying the inline styles of the components. Create a file named `app.R` with the following code:

    library(dash)
    library(dashCoreComponents)

    app <- dash_app()

    colors <- list(
      background = '#111111',
      text = '#7FDBFF'
    )

    app %>% set_layout(
      div(
        h1(
          'Hello Dash',
          style = list(
            textAlign = 'center',
            color = colors$text
          )
        ),
        div(
          'Dash for R: A web application framework for R.',
          style = list(
            textAlign = 'center',
            color = colors$text
          )
        ),
        dccGraph(
          id = 'example-graph-2',
          figure = list(
            data = list(
              list(
                x = list(1, 2, 3),
                y = list(4, 1, 2),
                type = 'bar',
                name = 'SF'
              ),
              list(
                x = list(1, 2, 3),
                y = list(2, 4, 5),
                type = 'bar',
                name = 'Montr\U{00E9}al'
              )
            ),
            layout = list(
              plot_bgcolor = colors$background,
              paper_bgcolor = colors$background,
              font = list(color = colors$text)
            )
          )
        ),
        style = list(backgroundColor = colors$background)
      )
    )

    app %>% run_app()

# Hello Dash

Dash: A web application framework for your data.

In this example, we modified the inline styles of the title `h1` and subtitle `div`components with the `style` property.

    h1(
      'Hello Dash',
      style = list(
        textAlign = 'center',
        color = '#7FDBFF'
      )
    )

The above code is rendered in the Dash app as `<h1 style="text-align: center; color: #7FDBFF">Hello Dash</h1>`.

There are a few important differences between the Dash HTML components and the HTML attributes:

1. The `style` property in HTML is a semicolon-separated string. In Dash, you can just supply a named list.
2. The names in the `style` list are camelCased. So, instead of `text-align`, it's `textAlign`.
3. The HTML `class` attribute is `className` in Dash.
4. The HTML `for` attribute is `htmlFor` in Dash.
5. A special property `n_clicks` is automatically added to every HTML tag. This property represents the number of times that an HTML element has been clicked on, which is mostly useful for `<button>`s. If not explicitly initialized to a certain integer, its default value is `NULL` initially.

Besides that, all of the available HTML attributes and tags are available to you within your R context.

A few more useful tips for Dash HTML components:

1. Named arguments with a value of `NULL` will not get rendered. This can be useful for conditionally including an attribute.
2. Named arguments with a value of `NA` will be rendered as boolean attributes.

### Reusable Components

By writing our markup in R, we can create complex reusable components like tables without switching contexts or languages.

Here's a quick example that generates a `Table` from a CSV file. Create a file named `app.R` with the following code:

    library(dash)
    library(dashCoreComponents)

    df <- read.csv(url("https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv"))

    generate_table <- function(df, nrows = 10) {
      nrows <- min(nrows, nrow(df))
      rows <- lapply(
        seq(nrows),
        function(row) {
          html$tr(lapply(as.character(df[row, ]), html$td))
        }
      )
      header <- html$td(children = lapply(names(df), html$th))
      html$table(
        c(list(header), rows)
      )
    }

    app <- dash_app()

    app %>% set_layout(
      div(
        h4('US Agriculture Exports (2011)'),
        generate_table(df),
        style= list("overflow-x" = "scroll")
      )
    )

    app %>% run_app()

#### US Agriculture Exports (2011)

Unnamed: 0 | state | total exports | beef | pork | poultry | dairy | fruits fresh | fruits proc | total fruits | veggies fresh | veggies proc | total veggies | corn | wheat | cotton
--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | ---
0 | Alabama | 1390.63 | 34.4 | 10.6 | 481 | 4.06 | 8 | 17.1 | 25.11 | 5.5 | 8.9 | 14.33 | 34.9 | 70 | 317.61
1 | Alaska | 13.31 | 0.2 | 0.1 | 0 | 0.19 | 0 | 0 | 0 | 0.6 | 1 | 1.56 | 0 | 0 | 0
2 | Arizona | 1463.17 | 71.3 | 17.9 | 0 | 105.48 | 19.3 | 41 | 60.27 | 147.5 | 239.4 | 386.91 | 7.3 | 48.7 | 423.95
3 | Arkansas | 3586.02 | 53.2 | 29.4 | 562.9 | 3.53 | 2.2 | 4.7 | 6.88 | 4.4 | 7.1 | 11.45 | 69.5 | 114.5 | 665.44
4 | California | 16472.88 | 228.7 | 11.1 | 225.4 | 929.95 | 2791.8 | 5944.6 | 8736.4 | 803.2 | 1303.5 | 2106.79 | 34.6 | 249.3 | 1064.95
5 | Colorado | 1851.33 | 261.4 | 66 | 14 | 71.94 | 5.7 | 12.2 | 17.99 | 45.1 | 73.2 | 118.27 | 183.2 | 400.5 | 0
6 | Connecticut | 259.62 | 1.1 | 0.1 | 6.9 | 9.49 | 4.2 | 8.9 | 13.1 | 4.3 | 6.9 | 11.16 | 0 | 0 | 0
7 | Delaware | 282.19 | 0.4 | 0.6 | 114.7 | 2.3 | 0.5 | 1 | 1.53 | 7.6 | 12.4 | 20.03 | 26.9 | 22.9 | 0
8 | Florida | 3764.09 | 42.6 | 0.9 | 56.9 | 66.31 | 438.2 | 933.1 | 1371.36 | 171.9 | 279 | 450.86 | 3.5 | 1.8 | 78.24
9 | Georgia | 2860.84 | 31 | 18.9 | 630.4 | 38.38 | 74.6 | 158.9 | 233.51 | 59 | 95.8 | 154.77 | 57.8 | 65.4 | 1154.07

> In fact, creating simple tables like this is such a common task that Dash provides a special function for it: `simple_table()`. You can also use `dash::dashDataTable()` for more complex tables.

### More about Visualization

The `DashCoreComponents` package includes a component called `dccGraph`.

`dccGraph` renders interactive data visualizations using the open source plotly.js JavaScript graphing library. Plotly.js supports over 35 chart types and renders charts in both vector-quality SVG and high-performance WebGL.

The `figure` argument in the`dccGraph` component is the same `figure` argument that is used by `plotly.py`, Plotly's open source graphing library. Check out the plotly.py documentation and gallery to learn more.

Here's an example that creates a scatter plot from a CSV file. Create a file named `app.R` with the following code:

    library(dash)
    library(dashCoreComponents)

    df <- read.csv(
      file = "https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv",
      stringsAsFactor = FALSE,
      check.names = FALSE
    )

    continents <- unique(df$continent)

    data_gdp_life_exp_2007 <- lapply(
      continents,
      function(cont) {
        list(
          x = df$gdpPercap[df$continent == cont],
          y = df$lifeExp[df$continent == cont],
          opacity = 0.7,
          text = df$country[df$continent == cont],
          mode = 'markers',
          name = cont,
          marker = list(size = 15, line = list(width = 0.5, color = 'white'))
        )
      }
    )

    app <- dash_app()

    app %>% set_layout(
      dccGraph(
        id = 'life-exp-vs-gdp',
        figure = list(
          data =  data_gdp_life_exp_2007,
          layout = list(
            xaxis = list('type' = 'log', 'title' = 'GDP Per Capita'),
            yaxis = list('title' = 'Life Expectancy'),
            margin = list('l' = 40, 'b' = 40, 't' = 10, 'r' = 10),
            legend = list('x' = 0, 'y' = 1),
            hovermode = 'closest'
          )
        )
      )
    )

    app %>% run_app()

These graphs are interactive and responsive. Hover over points to see their values, click on legend items to toggle traces, click and drag to zoom, hold down shift, and click and drag to pan.

### Markdown

While Dash exposes HTML through `DashHtmlComponents`, it can be tedious to write your copy in HTML. For writing blocks of text, you can use the `dccMarkdown` component in `DashCoreComponents`. Create a file named `app.R` with the following code:

    library(dash)
    library(dashCoreComponents)

    markdown_text <- "
    ### Dash and Markdown

    Dash apps can be written in Markdown.
    Dash uses the [CommonMark](http://commonmark.org/)
    specification of Markdown.
    Check out their [60 Second Markdown Tutorial](http://commonmark.org/help/)
    if this is your first introduction to Markdown!
    "

    dash_app() %>%
      set_layout(dccMarkdown(markdown_text)) %>%
      run_app()

### Dash and Markdown

Dash apps can be written in Markdown. Dash uses the CommonMark specification of Markdown. Check out their 60 Second Markdown Tutorial if this is your first introduction to Markdown!

### Core Components

`DashCoreComponents` includes a set of higher-level components like dropdowns, graphs, markdown blocks, and more.

Like all Dash components, they are described entirely declaratively. Every option that is configurable is available as a keyword argument of the component.

We'll see many of these components throughout the tutorial. You can view all of the available components in the Dash Core Components overview.

Here are a few of the available components. Create a file named `app.R` with the following code:

    library(dash)
    library(dashCoreComponents)

    app <- dash_app()

    app %>% set_layout(
      div(
        html$label('Dropdown'),
        dccDropdown(
          options = list(list(label = "New York City", value = "NYC"),
                         list(label = "Montreal", value = "MTL"),
                         list(label = "San Francisco", value = "SF")),
          value = 'MTL'
        ),

        html$label('Multi-Select Dropdown'),
        dccDropdown(
          options = list(list(label = "New York City", value = "NYC"),
                         list(label = "Montreal", value = "MTL"),
                         list(label = "San Francisco", value = "SF")),
          value = list('MTL', 'SF'),
          multi = TRUE
        ),

        html$label('Radio Items'),
        dccRadioItems(
          options = list(list(label = "New York City", value = "NYC"),
                         list(label = "Montreal", value = "MTL"),
                         list(label = "San Francisco", value = "SF")),
          value = 'MTL'
        ),

        html$label('Checkboxes'),
        dccChecklist(
          options = list(list(label = "New York City", value = "NYC"),
                         list(label = "Montreal", value = "MTL"),
                         list(label = "San Francisco", value = "SF")),
          value = list('MTL', 'SF')
        ),

        html$label('Text Input'),
        dccInput(value = 'MTL', type = 'text'),

        html$label('Slider'),
        dccSlider(
          min = 0,
          max = 9,
          marks = c("", "Label 1", 2:5),
          value = 5
        ),
        style = list('columnCount' = 2)
      )
    )

    app %>% run_app()

Dropdown
Montréal
×
Multi-Select Dropdown
×Montréal
×San Francisco
×
Radio Items
New York City Montréal San Francisco
Checkboxes
New York City Montréal San Francisco
Text Input
Slider
Label 1 2 3 4 5

### Help

Dash components are declarative: every configurable aspect of these components is set during instantiation as a keyword argument.

Call `?` in your R terminal on any of the components to learn more about a component and its available arguments.

    > ?dccDropdown

### Summary

The `layout` of a Dash app describes what the app looks like. The `layout` is a hierarchical tree of components, or a list of components (in Dash 2.17 and later).

The Dash package provides functions for all of the HTML tags and the keyword arguments describe the HTML attributes like `style`, `class`, and `id`. The `DashCoreComponents` package generates higher-level components like controls and graphs.

For reference, see:

- Dash Core Components overview
- Dash HTML Components overview

The next part of the Dash Fundamentals covers how to make these apps interactive. Dash Fundamentals Part 2: Basic Callbacks