16.3 Creating your own widgets

16.3.1 Requirements

To implement a widget, you can create a new R package that in turn depends on the htmlwidgets package. You can install the package from CRAN as follows:

install.packages("htmlwidgets")

While it is not strictly required, the step-by-step instructions below for getting started also make use of the devtools package, which you can also install from CRAN:

install.packages("devtools")

It is also possible to implement a widget without creating an R package, but it requires you to understand more about HTML dependencies (htmltools::htmlDependency()). We have given an example in Section 16.5.

16.3.2 Scaffolding

To create a new widget, you can call the scaffoldWidget() function to generate the basic structure for your widget. This function will:

  • Create the .R, .js, and .yaml files required for your widget;

  • If provided, take a Bower package name and automatically download the JavaScript library (and its dependencies) and add the required entries to the .yaml file.

This method is highly recommended, as it ensures that you get started with the right file structure. Here is an example that assumes you want to create a widget named ‘mywidget’ in a new package of the same name:

# create package using devtools
devtools::create("mywidget")

# navigate to package dir
setwd("mywidget")

# create widget scaffolding
htmlwidgets::scaffoldWidget("mywidget")

# install the package so we can try it
devtools::install()

This creates a simple widget that takes a single text argument and displays that text within the widgets HTML element. You can try it like this:

library(mywidget)
mywidget("hello, world")

This is the most minimal widget possible, and does not yet include a JavaScript library to interface to (note that scaffoldWidget() can optionally include JavaScript library dependencies via the bowerPkg argument). Before getting started with development, you should review the introductory example above to make sure you understand the various components, and also review the additional articles and examples linked to in the next section.

16.3.3 Other packages

Studying the source code of other packages is a great way to learn more about creating widgets:

  1. The networkD3 package illustrates creating a widget on top of D3, using a custom sizing policy for a larger widget, and providing multiple widgets from a single package.

  2. The dygraphs package illustrates using widget instance data, handling dynamic re-sizing, and using magrittr to decompose a large and flat JavaScript API into a more modular and pipeable R API.

  3. The sparkline package illustrates providing a custom HTML generation function (since sparklines must be housed in <span> rather than <div> elements).

If you have questions about developing widgets or run into problems during development, please do not hesitate to post an issue on the project’s GitHub repository: https://github.com/ramnathv/htmlwidgets/issues.