Chapter 8. Shiny and HTML/JavaScript

As it was already explained in the introduction, Shiny has practically no boundaries. Apart from the built-in capabilities that the package provides, the developer can also code their own HTML document instead of the UI.R file.

This HTML document is as any other document of its kind and can include the same things (for example, CSS, jQuery, JavaScript, and so on). In fact, UI.R files are, as it was previously mentioned, a mere wrapper that generates an HTML document with JavaScript, CSS, and so on.

This chapter is focused on the inclusion of custom JavaScript or CSS code in a Shiny application. In this sense, it is important to consider that it is not a JavaScript or CSS tutorial, and not even an introduction; it simply illustrates the different ways of including a few pieces of code from the previously mentioned languages in Shiny. This chapter is divided into the following four sections:

  • The www directory
  • Creating UIs from plain HTML
  • Using tags
  • Relating HTML/JavaScript and server.R

The www directory

The www directory is the directory expected by a Shiny application to locally store the elements that will be rendered in the web browser and are not the output of the scripts. This includes images, HTML, .js files, and so on. This directory must be at the same level as UI.R and server.R, that is, on the application's main folder.

Back to the first example, if we would like to include an image of the R logo that is stored as Rlogo.jpg before the number input, the code will be as follows in UI.R:

library(shiny)

# Starting line
shinyUI(fluidPage(

  # Application title
  titlePanel("Example 1"),
  
  # Sidebar with a numeric input
  # Sidebar
  sidebarLayout(
  sidebarPanel(
    img(src="Rlogo.jpg"),
    numericInput("number",
      "Insert a number:",
      value = 30,
      min = 1,
      max = 50)),


    #The plot created in server.R is displayed
    mainPanel(
      plotOutput("plot")
    )
  )
))

This folder is the destination of the files generated in the following sections. For this reason, it is always necessary to keep in mind that if the application needs any external document, this should be included in this www folder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset