What is the procedure for adding a personalized header to a table displayed in DT Shiny using code from another module?

Getting started with modularizing in R Shiny using namespaces can be a bit challenging at first. In the code below, split into "Core App Code" and "Module Code", the reactive object `iris1` is passed between these sections for use across different functions. The code incorporates parameters in the module server function calls and their definitions. It involves assigning the return value from one module to a reactive in the main server function and then passing that reactive to the second module via its server function.

Everything seems to be working fine except for the custom header (a secondary header styled in CSS within the `myContainer` function in the Module Code) that should span multiple columns above the DT table headers but isn't functioning properly. Can you spot what I might be doing wrong?

Code App Code:

library(shiny)
library(DT)

source("C:/Users/.../my_module.R") 

ui <- fluidPage(
  numericInput("number", label = "Enter sepal length multiplier:", value = 1),
  DTOutput('tbl')
)

server <- function(input, output) {
  iris1 <- reactive({
    tmp <- iris
    tmp$Sepal.Length <- tmp$Sepal.Length * input$number
    tmp
  })
  
  output$tbl <- renderDT({renderTable(iris1())})
  
  # Pass the reactive object iris1 to the module server function
  callModule(my_module_server, "myModule", iris1 = iris1)
}

shinyApp(ui, server)

Module Code (saved as my_module.R):

myContainer <- function() {
  htmltools::withTags(table(
    class = 'display',
    thead(
      tr(
        th(style = "border-top: none;border-bottom: none;"),
        th(colspan = 4, 'Lengths and widths',
           class = "dt-center",
           style = "border-right: solid 0.5px;border-left: solid 0.5px;border-top: solid 0.5px; background-color:#E6E6E6;"
        )
      ),
      tr(
        th(),
        lapply(names(iris1()), th)  # Access iris1 reactive object
      )
    )
  ))
}

renderTable <- function(data) {
  datatable(
    data,
    container = myContainer(),
    options = list(lengthChange = FALSE)
  )
}

my_module_ui <- function(id) {
  ns <- NS(id)
  DTOutput(ns("tbl"))
}

my_module_server <- function(input, output, session, iris1) {
  output$tbl <- renderDT({
    renderTable(
      iris1()  # Access iris1 reactive object
    )
  })
}

Answer №1

Presented here is a functional example of modularized code. By incorporating a module into your code, you may unknowingly fail to utilize it effectively. Specifically, the tbl output is generated within the main server and only this output is integrated into the primary UI.

In my revision, I have integrated the module UI directly into the main UI and eliminated the output$tbl from the main server along with its respective render function. Furthermore, to enhance efficiency, I have ensured that the myContainer function operates independently by passing table names as arguments instead of depending on a reactive defined elsewhere in the application. Running your initial code resulted in an error due to this setup. Moreover, there seems to be no valid reason for replacing shiny::renderTable with a custom function. If a customized function is indeed necessary, it is recommended to distinguish it with a unique name. Finally, I have transitioned to new-style modules utilizing moduleServer instead of relying on callModule.

library(shiny)
library(DT)

myContainer <- function(x) {
  htmltools::withTags(table(
    class = "display",
    thead(
      tr(
        th(style = "border-top: none;border-bottom: none;"),
        th(
          colspan = 4, "Lengths and widths",
          class = "dt-center",
          style = "border-right: solid 0.5px;border-left: solid 0.5px;border-top: solid 0.5px; background-color:#E6E6E6;"
        )
      ),
      tr(
        th(),
        lapply(x, th)
      )
    )
  ))
}

my_module_ui <- function(id) {
  ns <- NS(id)
  DTOutput(ns("tbl"))
}

my_module_server <- function(id, iris1) {
  moduleServer(id, function(input, output, session) {
    output$tbl <- renderDT({
      datatable(
        iris1(),
        container = myContainer(names(iris1())),
        options = list(lengthChange = FALSE)
      )
    })
  })
}

ui <- fluidPage(
  numericInput("number", label = "Enter sepal length multiplier:", value = 1),
  my_module_ui("myModule")
)

server <- function(input, output) {
  iris1 <- reactive({
    tmp <- iris
    tmp$Sepal.Length <- tmp$Sepal.Length * input$number
    tmp
  })

  my_module_server("myModule", iris1 = iris1)
}

shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:3641

https://i.sstatic.net/taFUZ.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

perform an action if any division element is void of content

Currently, I have a statement that checks if any of the Divs with the ID #Drop are empty. If one is found to be empty, an alert is shown. However, there seems to be an issue where the statement stops working when any div contains content. What I am trying ...

Struggling to connect CSS to HTML on Github Pages

I'm new to using Github, and I noticed that when I open the website, my HTML code is displaying without the associated CSS. Here is a snippet of my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...

What is causing the extra space in Flexbox layout?

Currently, I am in the process of coding a layout that requires me to evenly distribute cards next to each other in rows using flex. However, I am encountering an issue with spacing on the right side and I cannot pinpoint the exact reason behind it. After ...

Overflow-x in HTML5 Websites

I recently launched my website in the "alpha" stage - I have implemented full mobile support using media queries. It displays perfectly when the browser window is resized, but I noticed a strange space to the right of everything on my Samsung Galaxy Note ...

Responsive div not displaying background image

Here is a straightforward and easy-to-understand code snippet: HTML markup: <div class="jumbotron text-center top-jumbotron"> </div> CSS: .top-jumbotron { background: #ffcc00; background-image: url('../../bootstrap/img/home-pag ...

Basic selection menu layout

I have put together a basic menu for my WordPress site without relying on classes or IDs: <div class="main-menu"> <nav> <ul> <li> <a href="#" class="menu-link">home</a> ...

issue arising where the table's border is not displaying

I'm confused about why the border of the first tbody tr's td is not visible. https://i.stack.imgur.com/Fwlv7.png I can't see any reason why the border is not showing up. Here's what I've figured out: If the natural height of th ...

Filtering columns according to specified columns and values

How can we filter in R using either tidyverse or data.table when given lists of columns and corresponding values? The first list specifies the columns to be filtered, while the second list contains the values that should be selected for those columns. li ...

Finding elements in CSS using a partial tag name selector

I'm currently looking for an element in the following HTML structure: <first-name-grid> <div> some text .. </div> </first-name-grid> Is there a CSS locator equivalent to this Xpath method? let firstNameCssLocator : string = ...

What is preventing me from using JavaScript to remove this class?

Struggling to implement a skeleton loading screen with CSS classes and JavaScript. The idea is to apply the 'skeleton' class to elements, style them accordingly, then remove the class using a timeout set in JavaScript. However, I'm encounter ...

Having trouble getting the pagination bootstrap class to work properly? Here are some tips to help

Here is a portion of my pagination code utilizing Bootstrap. However, the styling properties of Bootstrap do not seem to be applied. What should I do? <ul class="pagination" > <?php // if($page_no > 1){ echo "<li>& ...

The functionality of dplyr's count appears to be malfunctioning within a function

My current issue involves printing aggregate tables and plots for various columns, but I encounter the error 'object not found' when passing a column name as an argument. To illustrate, consider the following: df <- data.frame( "age&quo ...

Combining data frames efficiently without replicating data in cases where multiple matches exist

I am looking to combine two data frames without duplicating rows or data if there are multiple matches. I want to avoid ambiguous matches and keep each row separate. So far, I have tried using the merge function, but it results in all possible matches cont ...

Is it advisable to incorporate CSS variables in place of traditional HTML color names?

As an illustration, I frequently utilize the color white in my CSS code. :root { --color-white: #fff; } I am curious if it is beneficial to define colors such as 'black' and 'white' as variables or if I should stick to using the def ...

Issues with the alignment of spans

What is the reason behind the *asdf being aligned to the bottom of its parent div in the following HTML code? <html> <style> .tag_editor { float: none; width: 400px; height: 33px; border-style: solid; border-color: #B2B2B2; border-width: thin; ...

Creating visual representations of the mean values across various columns using ggplot2

I am working with a dataset that contains marks for multiple questions across different IDs. ID, Q1, Q2, Q3, Q4, Q5 R1, 4, 3, 3, 2, 1 R2, 3, 2, 3, 2, 4 R3, 5, 1, 3, 4, 3 R4, 1, 3, 3, 5, 3 ... ... I am interested in creating a plot to ...

Injecting SVG styling into HTML using the content tag and CSS

I am working with 3 different files: index.html <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="style.css" /> </head> <body> <i class="logo myRed" aria-hidden="true"></i> ...

Dynamic manipulation of classes based on user attributes

One thing I've noticed is that certain WordPress themes, like 'Thematic', include user-specific classes in the body element to avoid using CSS browser hacks. For example: wordpress y2010 m02 d26 h05 home singular slug-home page pageid-94 pa ...

How can I adjust the size of an element without causing the other elements to move around on the

Currently, I am working on a live web page. You can view it at the following address: The issue I am facing is with the element just before the body's closing tag, the div "games_grid." When hovering over the game capsule image, it expands, causing t ...

Font consistency varies between different operating systems or machines

I have been experiencing a strange issue with the "Populaire" font that I am using. On my laptop, the font appears perfectly without any distortion on all browsers. However, when viewed on other systems (not all, but some), it becomes distorted across all ...