| Dash | R Documentation |
A framework for building analytical web applications, Dash offers a pleasant and productive development experience. No JavaScript required.
An R6::R6Class generator object
serverA cloned (and modified) version of the fiery::Fire object
provided to the server argument (various routes will be added which enable
Dash functionality).
configA list of configuration options passed along to dash-renderer. Users shouldn't need to alter any of these options unless they are constructing their own authorization front-end or otherwise need to know where the application is making API calls.
new()Create and configure a Dash application.
Dash$new( server = fiery::Fire$new(), assets_folder = "assets", assets_url_path = "/assets", eager_loading = FALSE, assets_ignore = "", serve_locally = TRUE, meta_tags = NULL, url_base_pathname = "/", routes_pathname_prefix = NULL, requests_pathname_prefix = NULL, external_scripts = NULL, external_stylesheets = NULL, compress = TRUE, suppress_callback_exceptions = FALSE, show_undo_redo = FALSE, update_title = "Updating..." )
serverfiery::Fire object. The web server used to power the application.
assets_folderCharacter. A path, relative to the current working directory,
for extra files to be used in the browser. All .js and
.css files will be loaded immediately unless excluded by assets_ignore,
and other files such as images will be served if requested. Default is assets.
assets_url_pathCharacter. Specify the URL path for asset serving. Default is assets.
eager_loadingLogical. Controls whether asynchronous resources are prefetched (if TRUE) or loaded on-demand (if FALSE).
assets_ignoreCharacter. A regular expression, to match assets to omit from immediate loading. Ignored files will still be served if specifically requested. You cannot use this to prevent access to sensitive files.
serve_locallyLogical. Whether to serve HTML dependencies locally or remotely (via URL).
meta_tagsList of lists. HTML <meta> tags to be added to the index page.
Each list element should have the attributes and values for one tag, eg:
list(name = 'description', content = 'My App').
url_base_pathnameCharacter. A local URL prefix to use app-wide. Default is
/. Both requests_pathname_prefix and routes_pathname_prefix default to url_base_pathname.
Environment variable is DASH_URL_BASE_PATHNAME.
routes_pathname_prefixCharacter. A prefix applied to the backend routes.
Environment variable is DASH_ROUTES_PATHNAME_PREFIX.
requests_pathname_prefixCharacter. A prefix applied to request endpoints
made by Dash's front-end. Environment variable is DASH_REQUESTS_PATHNAME_PREFIX.
external_scriptsList. An optional list of valid URLs from which
to serve JavaScript source for rendered pages. Each entry can be a string (the URL)
or a named list with src (the URL) and optionally other <script> tag attributes such
as integrity and crossorigin.
external_stylesheetsList. An optional list of valid URLs from which
to serve CSS for rendered pages. Each entry can be a string (the URL) or a list
with href (the URL) and optionally other <link> tag attributes such as
rel, integrity and crossorigin.
compressLogical. Whether to try to compress files and data served by Fiery.
By default, brotli is attempted first, then gzip, then the deflate algorithm,
before falling back to identity.
suppress_callback_exceptionsLogical. Whether to relay warnings about possible layout mis-specifications when registering a callback.
show_undo_redoLogical. Set to TRUE to enable undo and redo buttons for
stepping through the history of the app state.
update_titleCharacter. Defaults to Updating...; configures the document.title
(the text that appears in a browser tab) text when a callback is being run.
Set to NULL or ” if you don't want the document.title to change or if you
want to control the document.title through a separate component or
clientside callback.
server_route()Connect a URL to a custom server route
Dash$server_route(path = NULL, handler = NULL, methods = "get")
pathCharacter. Represents a URL path comprised of strings, parameters (strings prefixed with :), and wildcards (*), separated by /. Wildcards can be used to match any path element, rather than restricting (as by default) to a single path element. For example, it is possible to catch requests to multiple subpaths using a wildcard. For more information, see Route.
handlerFunction. Adds a handler function to the specified method and path. For more information, see Route.
methodsCharacter. A string indicating the request method (in lower case,
e.g. 'get', 'put', etc.), as used by reqres. The default is get.
For more information, see Route.
fiery, the underlying web service framework upon which Dash for R is based,
supports custom routing through plugins. While convenient, the plugin API
providing this functionality is different from that provided by Flask, as
used by Dash for Python. This method wraps the pluggable routing of routr
routes in a manner that should feel slightly more idiomatic to Dash users.
It is possible to retrieve the list of user-defined routes by invoking the
get_data method. For example, if your Dash application object is app, use
app$server$get_data("user-routes").
If you wish to erase all user-defined routes without instantiating a new Dash
application object, one option is to clear the routes manually:
app$server$set_data("user-routes", list()).
library(dash)
app <- Dash$new()
# A handler to redirect requests with `307` status code (temporary redirects);
# for permanent redirects (`301`), see the `redirect` method described below
#
# A simple single path-to-path redirect
app$server_route('/getting-started', function(request, response, keys, ...) {
response$status <- 307L
response$set_header('Location', '/layout')
TRUE
})
# Example of a redirect with a wildcard for subpaths
app$server_route('/getting-started/*', function(request, response, keys, ...) {
response$status <- 307L
response$set_header('Location', '/layout')
TRUE
})
# Example of a parameterized redirect with wildcard for subpaths
app$server_route('/accounts/:user_id/*', function(request, response, keys, ...) {
response$status <- 307L
response$set_header('Location', paste0('/users/', keys$user_id))
TRUE
})
redirect()Redirect a Dash application URL path
Dash$redirect(old_path = NULL, new_path = NULL, methods = "get")
old_pathCharacter. Represents the URL path to redirect, comprised of strings, parameters (strings prefixed with :), and wildcards (*), separated by /. Wildcards can be used to match any path element, rather than restricting (as by default) to a single path element. For example, it is possible to catch requests to multiple subpaths using a wildcard. For more information, see Route.
new_pathCharacter or function. Same as old_path, but represents the
new path which the client should load instead. If a function is
provided instead of a string, it should have keys within its formals.
methodsCharacter. A string indicating the request method
(in lower case, e.g. 'get', 'put', etc.), as used by reqres. The
default is get. For more information, see Route.
This is a convenience method to simplify adding redirects
for your Dash application which automatically return a 301
HTTP status code and direct the client to load an alternate URL.
library(dash)
app <- Dash$new()
# example of a simple single path-to-path redirect
app$redirect("/getting-started", "/layout")
# example of a redirect using wildcards
app$redirect("/getting-started/*", "/layout/*")
# example of a parameterized redirect using a function for new_path,
# which requires passing in keys to take advantage of subpaths within
# old_path that are preceded by a colon (e.g. :user_id):
app$redirect("/accounts/:user_id/*", function(keys) paste0("/users/", keys$user_id))
layout_get()Retrieves the Dash application layout.
Dash$layout_get(render = TRUE)
renderLogical. If the layout is a function, should the function be
executed to return the layout? If FALSE, the function is returned as-is.
If render is TRUE, and the layout is a function,
the result of the function (rather than the function itself) is returned.
List or function, depending on the value of render (see above).
When returning an object of class dash_component, the default print
method for this class will display the corresponding pretty-printed JSON
representation of the object to the console.
layout()Set the Dash application layout (i.e., specify its user interface).
Dash$layout(value)
valueAn object of the dash_component class, which provides
a component or collection of components, specified either as a Dash
component or a function that returns a Dash component.
value should be either a
collection of Dash components (e.g., dccSlider, htmlDiv, etc) or
a function which returns a collection of components. The collection
of components must be nested, such that any additional components
contained within value are passed solely as children of the top-level
component. In all cases, value must be a member of the dash_component
class.
react_version_set()Update the version of React in the list of dependencies served by dash-renderer to the client.
Dash$react_version_set(version)
versionCharacter. The version number of React to use.
callback()Define a Dash callback.
Dash$callback(output, params, func)
outputNamed list. The output argument provides the component id
and property which will be updated by the callback; a callback can
target one or more outputs (i.e. multiple outputs).
paramsUnnamed list; provides input and state statements, each
with its own defined id and property. For pattern-matching callbacks,
the id field of a component is written in JSON-like syntax and provides
fields that are arbitrary keys which describe the targets of the callback.
See selectors for more details.
funcFunction; must return output provided input or state
arguments. func may be any valid R function, or a character string
containing valid JavaScript, or a call to clientsideFunction,
including namespace and function_name arguments for a locally served
JavaScript function.
Describes a server or clientside callback relating the values of one or more
output items to one or more input items which will trigger the callback
when they change, and optionally state items which provide additional
information but do not trigger the callback directly.
For detailed examples of how to use pattern-matching callbacks, see the entry for selectors or visit our interactive online documentation at https://dash.plotly.com/r/.
The output argument defines which layout component property should
receive the results (via the output object). The events that
trigger the callback are then described by the input (and/or state)
object(s) (which should reference layout components), which become
argument values for R callback handlers defined in func.
Here func may either be an anonymous R function, a JavaScript function
provided as a character string, or a call to clientsideFunction(), which
describes a locally served JavaScript function instead. The latter
two methods define a "clientside callback", which updates components
without passing data to and from the Dash backend. The latter may offer
improved performance relative to callbacks written purely in R.
callback_context()Request and return the calling context of a Dash callback.
Dash$callback_context()
The callback_context method permits retrieving the inputs which triggered
the firing of a given callback, and allows introspection of the input/state
values given their names. It is only available from within a callback;
attempting to use this method outside of a callback will result in a warning.
The callback_context method returns a list containing three elements:
states, triggered, inputs. The first and last of these correspond to
the values of states and inputs for the current invocation of the
callback, and triggered provides a list of changed properties.
List comprising elements states, triggered, inputs.
callback_context.record_timing()Records timing information for a server resource.
Dash$callback_context.record_timing(name, duration = NULL, description = NULL)
nameCharacter. The name of the resource.
durationNumeric. The time in seconds to report. Internally, this is rounded to the nearest millisecond.
descriptionCharacter. A description of the resource.
The callback_context.record_timing method permits retrieving the
duration required to execute a given callback. It may only be called
from within a callback; a warning will be thrown and the method will
otherwise return NULL if invoked outside of a callback.
get_asset_url()Return a URL for a Dash asset.
Dash$get_asset_url(asset_path, prefix = self$config$requests_pathname_prefix)
asset_pathCharacter. Specifies asset filename whose URL should be returned.
prefixCharacter. Specifies pathname prefix; default is to use requests_pathname_prefix.
The get_asset_url method permits retrieval of an asset's URL given its filename.
For example, app$get_asset_url('style.css') should return /assets/style.css when
assets_folder = 'assets'. By default, the prefix is the value of requests_pathname_prefix,
but this is configurable via the prefix parameter. Note: this method will
present a warning and return NULL if the Dash app was not loaded via source()
if the DASH_APP_PATH environment variable is undefined.
Character. A string representing the URL to the asset.
get_relative_path()Return relative asset paths for Dash assets.
Dash$get_relative_path( path, requests_pathname_prefix = self$config$requests_pathname_prefix )
pathCharacter. A path string prefixed with a leading / which directs
at a path or asset directory.
requests_pathname_prefixCharacter. The pathname prefix for the application when
deployed. Defaults to the environment variable set by the server,
or "" if run locally.
The get_relative_path method simplifies the handling of URLs and pathnames for apps
running locally and on a deployment server such as Dash Enterprise. It handles the prefix
for requesting assets similar to the get_asset_url method, but can also be used for URL handling
in components such as dccLink or dccLocation. For example, app$get_relative_url("/page/")
would return /app/page/ for an app running on a deployment server. The path must be prefixed with
a /.
Character. A string describing a relative path to a Dash app's asset
given a path and requests_pathname_prefix.
strip_relative_path()Return a Dash asset path without its prefix.
Dash$strip_relative_path( path, requests_pathname_prefix = self$config$requests_pathname_prefix )
pathCharacter. A path string prefixed with a leading / which directs
at a path or asset directory.
requests_pathname_prefixCharacter. The pathname prefix for the app on
a deployed application. Defaults to the environment variable set by the server,
or "" if run locally.
The strip_relative_path method simplifies the handling of URLs and pathnames for apps
running locally and on a deployment server such as Dash Enterprise. It acts almost opposite to the get_relative_path
method, by taking a relative path as an input, and returning the path stripped of the requests_pathname_prefix,
and any leading or trailing /. For example, a path string /app/homepage/, would be returned as
homepage. This is particularly useful for dccLocation URL routing.
index_string()Specify a custom index string for a Dash application.
Dash$index_string(string)
stringCharacter; the index string template, with interpolation keys included.
The index_string method allows the specification of a custom index by changing
the default HTML template that is generated by the Dash UI. #' Meta tags, CSS, and JavaScript are some examples of features
that can be modified. This method will present a warning if your
HTML template is missing any necessary elements
and return an error if a valid index is not defined. The following interpolation keys are
currently supported:
{%metas%}Optional - The registered meta tags.
{%favicon%}Optional - A favicon link tag if found in assets.
{%css%}Optional - Link tags to CSS resources.
{%config%}Required - Configuration details generated by Dash for the renderer.
{%app_entry%}Required - The container where Dash React components are rendered.
{%scripts%}Required - Script tags for collected dependencies.
"<!DOCTYPE html>
<html>
<head>
{%meta_tags%}
<title>{{
{%favicon%}
{%css_tags%}
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
</footer>
</body>
</html>"
interpolate_index()Modify index template variables for a Dash application.
Dash$interpolate_index(template_index = private$template_index[[1]], ...)
template_indexCharacter. A formatted string with the HTML index string. Defaults to the initial template.
...Named list. The unnamed arguments can be passed as individual named lists corresponding to the components of the Dash HTML index. These include the same argument as those found in the index_string() template.
With the interpolate_index method, one can pass a custom index with template string
variables that are already evaluated. Directly passing arguments to the template_index
has the effect of assigning them to variables present in the template. This is similar to the index_string method
but offers the ability to change the default components of the Dash index as seen in the example below.
library(dash)
app <- Dash$new()
sample_template <- "<!DOCTYPE html>
<html>
<head>
{%meta_tags%}
<title>Index Template Test</title>
{%favicon%}
{%css_tags%}
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
</footer>
</body>
</html>"
# this is the default configuration, but custom configurations
# are possible -- the structure of the "config" argument is
# a list, in which each element is a JSON key/value pair, when
# reformatted as JSON from the list:
# e.g. {"routes_pathname_prefix":"/", "ui":false}
config <- sprintf("<script id='_dash-config' type='application/json'> %s </script>",
jsonlite::toJSON(app$config, auto_unbox=TRUE))
app$interpolate_index(
sample_template,
metas = "<meta_charset='UTF-8'/>",
app_entry = "<div id='react-entry-point'><div class='_dash-loading'>Loading...</div></div>",
config = config,
scripts = "")
title()Set the title of the Dash app
Dash$title(string = "Dash")
stringCharacter. A string representation of the name of the Dash application.
If no title is supplied, Dash for R will use 'Dash'.
run_server()Start the Fiery HTTP server and run a Dash application.
Dash$run_server(
host = Sys.getenv("HOST", "127.0.0.1"),
port = Sys.getenv("PORT", 8050),
block = TRUE,
showcase = FALSE,
use_viewer = FALSE,
dev_tools_prune_errors = TRUE,
debug = Sys.getenv("DASH_DEBUG"),
dev_tools_ui = Sys.getenv("DASH_UI"),
dev_tools_props_check = Sys.getenv("DASH_PROPS_CHECK"),
dev_tools_hot_reload = Sys.getenv("DASH_HOT_RELOAD"),
dev_tools_hot_reload_interval = Sys.getenv("DASH_HOT_RELOAD_INTERVAL"),
dev_tools_hot_reload_watch_interval = Sys.getenv("DASH_HOT_RELOAD_WATCH_INTERVAL)"),
dev_tools_hot_reload_max_retry = Sys.getenv("DASH_HOT_RELOAD_MAX_RETRY"),
dev_tools_silence_routes_logging = NULL,
...
)hostCharacter. A string specifying a valid IPv4 address for the Fiery server, or 0.0.0.0 to listen on all addresses. Default is 127.0.0.1 Environment variable: HOST.
portInteger. Specifies the port number on which the server should listen (default is 8050). Environment variable: PORT.
blockLogical. Start the server while blocking console input? Default is TRUE.
showcaseLogical. Load the Dash application into the default web browser when server starts? Default is FALSE.
use_viewerLogical. Load the Dash application into RStudio's viewer pane? Requires that host is either 127.0.0.1 or localhost, and that Dash application is started within RStudio; if use_viewer = TRUE and these conditions are not satisfied, the user is warned and the app opens in the default browser instead. Default is FALSE.
dev_tools_prune_errorsLogical. Reduce tracebacks such that only lines relevant to user code remain, stripping out Fiery and Dash references? Only available with debugging. TRUE by default, set to FALSE to see the complete traceback. Environment variable: DASH_PRUNE_ERRORS.
debugLogical. Enable/disable all the Dash developer tools (and the within-browser user interface for the callback graph visualizer and stack traces) unless overridden by the arguments or environment variables. Default is FALSE when called via run_server. For more information, please visit https://dash.plotly.com/r/devtools. Environment variable: DASH_DEBUG.
dev_tools_uiLogical. Show Dash's developer tools UI? Default is TRUE if debug == TRUE, FALSE otherwise. Environment variable: DASH_UI.
dev_tools_props_checkLogical. Validate the types and values of Dash component properties? Default is TRUE if debug == TRUE, FALSE otherwise. Environment variable: DASH_PROPS_CHECK.
dev_tools_hot_reloadLogical. Activate hot reloading when app, assets, and component files change? Default is TRUE if debug == TRUE, FALSE otherwise. Requires that the Dash application is loaded using source(), so that srcref attributes are available for executed code. Environment variable: DASH_HOT_RELOAD.
dev_tools_hot_reload_intervalNumeric. Interval in seconds for the client to request the reload hash. Default is 3. Environment variable: DASH_HOT_RELOAD_INTERVAL.
dev_tools_hot_reload_watch_intervalNumeric. Interval in seconds for the server to check asset and component folders for changes. Default 0.5. Environment variable: DASH_HOT_RELOAD_WATCH_INTERVAL.
dev_tools_hot_reload_max_retryInteger. Maximum number of failed reload hash requests before failing and displaying a pop up. Default 0.5. Environment variable: DASH_HOT_RELOAD_MAX_RETRY.
dev_tools_silence_routes_loggingLogical. Replace Fiery's default logger with dashLogger instead (will remove all routes logging)? Enabled with debugging by default because hot reload hash checks generate a lot of requests.
...Additional arguments to pass to the start handler; see the fiery documentation for relevant examples.
Starts the Fiery server in local mode and launches the Dash application. If a parameter can be set by an environment variable, that is listed too. Values provided here take precedence over environment variables.
. If provided, host/port set the host/port fields of the underlying fiery::Fire web server. The block/showcase/... arguments are passed along
to the ignite() method of the fiery::Fire server.
if (interactive() ) {
library(dash)
app <- Dash$new()
app$layout(htmlDiv(
list(
dccInput(id = "inputID", value = "initial value", type = "text"),
htmlDiv(id = "outputID")
)
)
)
app$callback(output = list(id="outputID", property="children"),
params = list(input(id="inputID", property="value"),
state(id="inputID", property="type")),
function(x, y)
sprintf("You've entered: '%s' into a '%s' input control", x, y)
)
app$run_server(showcase = TRUE)
}
clone()The objects of this class are cloneable with this method.
Dash$clone(deep = FALSE)
deepWhether to make a deep clone.
## ------------------------------------------------
## Method `Dash$server_route`
## ------------------------------------------------
library(dash)
app <- Dash$new()
# A handler to redirect requests with `307` status code (temporary redirects);
# for permanent redirects (`301`), see the `redirect` method described below
#
# A simple single path-to-path redirect
app$server_route('/getting-started', function(request, response, keys, ...) {
response$status <- 307L
response$set_header('Location', '/layout')
TRUE
})
# Example of a redirect with a wildcard for subpaths
app$server_route('/getting-started/*', function(request, response, keys, ...) {
response$status <- 307L
response$set_header('Location', '/layout')
TRUE
})
# Example of a parameterized redirect with wildcard for subpaths
app$server_route('/accounts/:user_id/*', function(request, response, keys, ...) {
response$status <- 307L
response$set_header('Location', paste0('/users/', keys$user_id))
TRUE
})
## ------------------------------------------------
## Method `Dash$redirect`
## ------------------------------------------------
library(dash)
app <- Dash$new()
# example of a simple single path-to-path redirect
app$redirect("/getting-started", "/layout")
# example of a redirect using wildcards
app$redirect("/getting-started/*", "/layout/*")
# example of a parameterized redirect using a function for new_path,
# which requires passing in keys to take advantage of subpaths within
# old_path that are preceded by a colon (e.g. :user_id):
app$redirect("/accounts/:user_id/*", function(keys) paste0("/users/", keys$user_id))
## ------------------------------------------------
## Method `Dash$interpolate_index`
## ------------------------------------------------
library(dash)
app <- Dash$new()
sample_template <- "<!DOCTYPE html>
<html>
<head>
{%meta_tags%}
<title>Index Template Test</title>
{%favicon%}
{%css_tags%}
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
</footer>
</body>
</html>"
# this is the default configuration, but custom configurations
# are possible -- the structure of the "config" argument is
# a list, in which each element is a JSON key/value pair, when
# reformatted as JSON from the list:
# e.g. {"routes_pathname_prefix":"/", "ui":false}
config <- sprintf("<script id='_dash-config' type='application/json'> %s </script>",
jsonlite::toJSON(app$config, auto_unbox=TRUE))
app$interpolate_index(
sample_template,
metas = "<meta_charset='UTF-8'/>",
app_entry = "<div id='react-entry-point'><div class='_dash-loading'>Loading...</div></div>",
config = config,
scripts = "")
## ------------------------------------------------
## Method `Dash$run_server`
## ------------------------------------------------
if (interactive() ) {
library(dash)
app <- Dash$new()
app$layout(htmlDiv(
list(
dccInput(id = "inputID", value = "initial value", type = "text"),
htmlDiv(id = "outputID")
)
)
)
app$callback(output = list(id="outputID", property="children"),
params = list(input(id="inputID", property="value"),
state(id="inputID", property="type")),
function(x, y)
sprintf("You've entered: '%s' into a '%s' input control", x, y)
)
app$run_server(showcase = TRUE)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.