16.3 Creating your own widgets
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:
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:
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.
To create a new widget, you can call the
scaffoldWidget() function to generate the basic structure for your widget. This function will:
.yamlfiles required for your widget;
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 ::create("mywidget") devtools # navigate to package dir setwd("mywidget") # create widget scaffolding ::scaffoldWidget("mywidget") htmlwidgets # install the package so we can try it ::install()devtools
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")
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:
The sparkline package illustrates providing a custom HTML generation function (since sparklines must be housed in
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.