I'm trying to create an HTML
object within R to have more flexibility with JS
code. However, I don't know how to introduce the id's of objects created with the HTML function inside reactive()
. I compared two cases. One with HTML()
and one with textInput()
. In the first case it doesn't work, in the second it does. I need to use HTML()
and not shiny tags
because I need to edit my code in more specific parts.
Code:
library(shiny)
library(shinydashboard)
header <- dashboardHeader(title = "Dashboard")
sidebar <- dashboardSidebar()
body <- dashboardBody(
HTML(
"<p>Type your name:</p>
<input id='inputxaxis'></input>
<br>"
),
valueBoxOutput(outputId = "box1", width = 6),
textInput(
inputId = "works",
label = "type your name:"
),
valueBoxOutput(outputId = "box2", width = 6),
)
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output) {
code1 <- reactive({
fx <- function(x) {
x
}
fx(
x = input$inputxaxis # doesn't work
)
})
code2 <- reactive({
fy <- function(y) {
y
}
fy(
y = input$works # rorks perfectly
)
})
output$box1 <- renderValueBox({
valueBox(
value = code1(),
subtitle = "Subtitle",
color = "red"
)
})
output$box2 <- renderValueBox({
valueBox(
value = code2(),
subtitle = "Subtitle",
color = "green"
)
})
}
shinyApp(ui, server)
CodePudding user response:
You need to add a JavaScript listener to send the input changes to the shiny server:
HTML(
"<p>Type your name:</p>
<input id='inputxaxis'></input>
<br>
<script>
document.getElementById('inputxaxis').addEventListener('change', sendToShiny);
function sendToShiny(event){
console.log(event);
Shiny.setInputValue('works_2', event.target.value);
}
</script>
"
)
Then you can access the input as you normally would:
code1 <- reactive({
req(input$works_2)
fx <- function(x) {
x
}
fx(
x = input$works_2
)
})
See more documentation here: Communicating with Shiny via JavaScript
CodePudding user response:
I think Ryan Morton's answer is really good for understanding how Shiny works and quite likely you will need to use the information in the link for your actual use.
However, in this particular case you can just replicate the html that is created by textInput()
. You can see what this is if you run your line directly in the R terminal (i.e. with the Shiny package loaded but not as part of a Shiny app):
textInput(
inputId = "works",
label = "type your name:"
)
Output:
<div >
<label for="works">type your name:</label>
<input id="works" type="text" value=""/>
</div>
If you simply change the input id to inputxaxis
and pop that in to replace your existing HTML()
function call, then as you've already written the rest of the code it should replicate the behaviour.
HTML(
'<div >
<label for="works">type your name:</label>
<input id="inputxaxis" type="text" value=""/>
</div>'
)