Leo
Leo

Reputation: 61

What is the difference between NS() and ns() (Rshiny)

NS() vs ns() When to use the upper Case variant and when to use the lower case?

Upvotes: 1

Views: 617

Answers (2)

Stéphane Laurent
Stéphane Laurent

Reputation: 84529

There is the NS function in the shiny package but there's no ns function.

It is common to do ns <- NS(id) in the UI part of a Shiny module, as shown in @Leo's answer (but you are not obliged to use the name ns). Then ns is a function: ns("something") returns the string "moduleId-something" if id = "moduleId". As @Leo said, you can equivalently do NS(id, "something"). That is to say, NS(id)("something") is the same as NS(id, "something").

library(shiny)

id <- "moduleId"
ns <- NS(id)
ns("something")
# "moduleId-something"
NS(id, "something")
# "moduleId-something"
NS(id)("something")
# "moduleId-something"
unusual_name <- NS(id)
unusual_name("something")
# "moduleId-something"

In the server part of a Shiny module you have session$ns at your disposal. For a non-nested module, session$ns is the same as NS(id). That is to say, ns <- session$ns; ns("something") is equivalent to NS(id)("something"). For a nested module, assuming the parent module is not nested, ns <- session$ns; ns("something") is the same as NS(parentid)(NS(id)("something")) where parentid is the module id of the parent module. So in the server part of a Shiny module it is better to use session$ns than NS(id) because session$ns will automatically handle the situation where modules are nested.

Upvotes: 2

Leo
Leo

Reputation: 61

In this piece of code ns is assigned to NS(id) now i can use ns("Name")

  mod_Navigation_ui <- function(id){
  ns <- NS(id)
  tagList(
    fluidPage(
      actionButton(ns("test"), "action"),
    )
   )}

If i delete the ns <- NS(id) I have to write:

mod_Navigation_ui <- function(id){
  tagList(
    fluidPage(
      actionButton(NS(id,"test"), "action"),
    )
  )}

Upvotes: 2

Related Questions