Context
Following this chapter in Javascript for R online book I cannot reproduce the last example and
I guess that is because <
is transformed into >
.
Reproducible steps
Packages needed
library(usethis)
library(htmlwidgets)
library(shiny)
Create the widget
create_package("playground")
scaffoldWidget("play")
Modify the code in play.R
change this section:
# forward options using x
x = list(
message = message
)
into this:
# forward options using x
x = list(
message = as.character(message)
)
Load package and use widget
document(); load_all()
play(h2("Some text!"))
Result
Expected
Formatted header
Effort
When inspecting the text, one can copy/paste the content of the div and see:
<div class="play html-widget html-fill-item-overflow-hidden html-fill-item html-widget-static-bound" id="htmlwidget-4a78c11ab194f4375219" style="width:960px;height:500px;"><h2>qwer</h2></div>
I guess the issue is coming from the >
that replaces the ‘>’ but I cannot see:
- where it is happening
- If it is expected
- If something has changed since the writing of the book
play.js
HTMLWidgets.widget({
name: 'play',
type: 'output',
factory: function(el, width, height) {
// TODO: define shared variables for this instance
return {
renderValue: function(x) {
// TODO: code to render the widget, e.g.
el.innerText = x.message;
},
resize: function(width, height) {
// TODO: code to re-render the widget with a new size
}
};
}
});
2
Answers
Your JavaScript file receives the character string
"<h2>qwer</h2>"
. You have to parse it to HTML. Since jQuery is available in htmlwidgets, you can use$.parseHTML
(applied to$(el)$
, the jQuery selection of the htmlwidgets element).You have
innerText
instead ofinnerHTML
in your code. This means you set the contents in such a way that the displayed text at the end is<h2>qwer</h2>
, so the angle brackets get escaped. You seem to want to actually set HTML contents though, so the angle brackets should get interpreted as HTML tags. That’s why you needinnerHTML
instead.