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 thehtmlwidgets 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 thedevtools 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 Section16.5.
16.3.2 Scaffolding
To create a new widget, you can call thescaffoldWidget() function to generate the basic structure for your widget. This function will:
Create the
.R,.js, and.yamlfiles required for your widget;If provided, take aBower package name and automatically download the JavaScript library (and its dependencies) and add the required entries to the
.yamlfile.
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 devtoolsdevtools::create("mywidget")# navigate to package dirsetwd("mywidget")# create widget scaffoldinghtmlwidgets::scaffoldWidget("mywidget")# install the package so we can try itdevtools::install()This creates a simple widget that takes a singletext 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 thatscaffoldWidget() can optionally include JavaScript library dependencies via thebowerPkg 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:
ThenetworkD3 package illustrates creating a widget on top ofD3, using a custom sizing policy for a larger widget, and providing multiple widgets from a single package.
Thedygraphs package illustrates using widget instance data, handling dynamic re-sizing, and usingmagrittr to decompose a large and flat JavaScript API into a more modular and pipeable R API.
Thesparkline 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.