NS() vs ns() When to use the upper Case variant and when to use the lower case?
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Dec 04 '22 at 21:05
2 Answers
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"),
)
)}

- 51
- 4
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.

- 75,186
- 15
- 119
- 225