What is the best way to transfer data from R to JS in a Shiny app and incorporate it into the user interface?

I am looking to add a custom news button to the header of my shinyapp, which will display information from a specific dataset. I want the button to show the number of news items available, similar to how

shinyDashboard::notificationItem()
works but with more customization. However, since I am new to JavaScript, I am unsure how to concatenate the strings 'News' and '5' to display 'News (5)' on the button.

In addition to displaying the news count, clicking the button should eventually render a new UI with the actual news content.

Any assistance on achieving this would be greatly appreciated!


library(shiny)

ui = navbarPage(title = "Dashboard", 

  tags$script(
    HTML(
      "Shiny.addCustomMessageHandler(
        type = 'num', function(message) {
          var newsCount = message
          var header = $('.navbar > .container-fluid');
          header.append('<div><input value = \"News (" + newsCount + \")\" type = \"button\" class = \"btn action-button\"></div>');
        });"
      
    )
  )
  
)
server = function(input, output, session){
  
  session$sendCustomMessage(type = "num", message = 5)
 
  

}
shinyApp(ui, server)

Answer №1

When working in JavaScript, strings can be combined using the + operator.

  tags$script(
    HTML(
      "Shiny.addCustomMessageHandler(
        type = 'num', function(message) {
          var ok = 'News (' + message + ')';
          var header = $('.navbar > .container-fluid');
          header.append('<div><button class = \"btn btn-primary action-button\">' + ok + '</button></div>');
        });"
    )
  )

To assign a specific color to the number:

  tags$script(
    HTML(
      "Shiny.addCustomMessageHandler(
        type = 'num', function(x) {
          var ok = '<span>News (<span style=\"color: red;\">' + x + '</span>)</span>';
          var header = $('.navbar > .container-fluid');
          header.append('<div><button class = \"btn btn-primary action-button\">' + ok + '</button></div>');
        });"
    )
  )

Answer №2

Here is an alternative approach that you might find useful:

ui <- navbarPage("Dashboard",
                 header = tags$script(
                   HTML("var headSection = $('.navbar > .container-fluid');
                        headSection.append('<div style=\"float:right; padding-top: 8px\"><button id=\"btn_show\" type=\"button\" class=\"btn btn-primary action-button\" onclick=\"displayContent()\">Click Me</button></div>')")
                 ),
                tabPanel("Information",
                         radioButtons("choose", "select option", choices = 1:4, inline = T))
)



server <- function(input, output, session) {
  
  observeEvent(input$choose, {
    updateActionButton(session,"btn_show", label = paste0("Details (", input$select, ")"))
  }, ignoreInit = T)

}

shinyApp(ui, server)

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

Simplified method for creating Angular templates

Take a look at this code snippet my_app.run( [ '$templateCache' , function( $templateCache ) { var template = "" + "{{ item.name }}" + "<ul ng-if='item.sub'>" + "& ...

Posting and deleting data in AngularJS using HTTP requests

Incorporating both angularjs and c# webapi in this situation. My approach involves calling the webapi from angularjs and passing a json array. Here is the Angularjs code snippet: factory.delete = function (json) { var url = 'myUrl'; ...

retrieve a string value from a function within a ReactJS component

I am facing an issue with returning a string from a function. Here is the function I am using: const getImage = (name) => { const imageRef = ref(storage, name); getDownloadURL(imageRef).then((url) => { return url; }); }; Even tho ...

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

Save to a JSON file

Hey there, I'm having some trouble with pushing a temporary value to a JSON file using the command "MyJSON.name.push". It keeps giving me an error saying "Undefined is not an object". I've tried different approaches and using JavaScript arrays wo ...

Issues with displaying markers on Google Maps API using JSON and AJAX

I have successfully coded the section where I retrieve JSON markers and loop through them. However, despite this, the markers do not seem to be appearing on the map. Could someone please assist me in identifying the mistake? $.ajax({ url ...

When the getImageData event is triggered upon loading

Hello, I have a script that identifies transparent and non-transparent pixels. Currently, the result is displayed from a 100px by 100px rectangle on mouseover: var data = ctx.getImageData(100,100, canvas.width, canvas.height).data; During mouseover, it s ...

Storing Array Data in Angular $scope (Javascript)

I am currently altering the Altair Material Design Template and incorporating an Angular JS controller. After successfully calling an API and creating variables in a for loop, I intend to write them to $scope.dragulaItems. While this process seems to work ...

What is the best way to deselect the first radio button while selecting the second one, and vice versa, when there are two separate radio groups?

I am looking to achieve a functionality where if the first radio button is selected, I should receive the value true and the second radio button should be unselected with the value false. Similarly, if the second radio button is selected, I should receive ...

Ways to retrieve an array following a function call

After a lot of testing and troubleshooting, I finally got my array to function properly in the console. However, when I click the button, the array is displayed on the console but not in my HTML. TS: jogar(){ for(var u=0;u<6;u++){ this.y ...

An Angular application running on an Azure App Service experiences crashes exclusively when accessed through the Chrome browser

My webapi/angular site is hosted on the same Azure app service, with authentication token and other APIs located at /site/api and the angular app at /site/app. Everything works fine on our staging environment, which is a Windows 2012 VM with IIS 7. The an ...

Cross-Origin Resource Sharing (CORS) in Ajax requests

I've been attempting to fetch variables from an external domain using AJAX and then populate pre-filled form fields with the retrieved data. However, I'm facing difficulties getting it to function properly. While I'm relatively new to JavaS ...

Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required... <button type="button" id= ...

Why is it that the HttpClient constructor in Angular doesn't require parameters when instantiated through the constructor of another class, but does when instantiated via the 'new' keyword?

I am trying to create a static method for instantiating an object of a class, but I have encountered a problem. import { HttpClient } from '@angular/common/http'; export MyClass { // Case 1 public static init(): MyClass { return this(new ...

Is Sending an Object to a Function in the Same Scope Inefficient?

Is there a noticeable delay when passing around an object within the same scope? Let's explore Option 1 and Option 2. In Option 1, we work directly with the object, while in Option 2 we follow better encapsulation practices. However, if we were to sti ...

Is it necessary for me to use bindActionCreators?

While going through a post, I couldn't help but notice that the bindActionCreators method from redux wasn't being utilized. Is there a specific reason for this? Could it be that the method is not necessary in this context? The post in question ...

Dependency injection of an Angular app factory toaster is causing the application to malfunction

I am currently working on an Angular application that utilizes Firebase as its backend. My goal is to inject 'toaster' as a dependency within my authorization app factory. Below is the initial setup of the app.factory: app.factory('principa ...

Having trouble with sending a list of items from a VueJS form

I have a VueJS application that calls a patch method to update a user's profile. For example, I am attempting to update the field cities. I created a serializer and views.py using Postman during development. I used Postman to call the patch method fo ...

What is the best way to automatically adjust a calculated value in R Shiny based on the quantity of input values?

In an R shiny app, I am working on updating a value in a plotly chart. This value is calculated based on the number of user inputs provided. library(shiny) library(httr) library(jsonlite) ... The issue I am facing is that the risk_profile plot displays co ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...