How to insert this JavaScript into my Quarto document?

75 views Asked by At

I am experimenting with passing information back and forth between html widgets, but I don't know what I'm doing.

I am using one function Reactable.onStateChange from this documentation:

https://glin.github.io/reactable/articles/javascript-api.html

This document renders but if I go into the browser tools, I see this error:

Uncaught Error: reactable instance 'myTable' not found
    at _i (reactable_state_change.html:4792:124046)
    at Object.rl [as onStateChange] (reactable_state_change.html:4792:124866)
    at reactable_state_change.html:4812:19
_i @ reactable_state_change.html:4792
rl @ reactable_state_change.html:4792
(anonymous) @ reactable_state_change.html:4812

I have tried to include the JavaScript in both the same chunk as the other widgets and also in a js chunk, but neither worked.

---
format: html
editor: source
self-contained: true
execute:
  echo: false
---

```{r}
#| message: false
library(reactable)
library(htmltools)
```

```{r}
dat <- data.frame(a = 1:5, b = 11:15)
tab <- reactable(dat, selection = "single", elementId = "myTable")
txt <- withTags(p(id = "mySelection"))
js <- tags$script(HTML(
  "Reactable.onStateChange('myTable', state => {document.getElementById('mySelection').innerHTML = state.selected})"
))
browsable(tagList(tab, txt, js))
```

```{js}
<!-- Reactable.onStateChange('myTable', state => {document.getElementById('mySelection').innerHTML = state.selected}) -->
```
2

There are 2 answers

0
Arthur On

I figured out one possible solution. The issue was realizing that there needs to be an event to trigger the call to onStateChange. Open to learning better ways to do it.

---
format: html
editor: source
self-contained: true
execute:
  echo: false
---

```{r}
#| message: false
library(reactable)
library(htmltools)
```

```{r}
dat <- data.frame(a = 1:5, b = 11:15)
tab <- reactable(dat, selection = "single", elementId = "myTable")
tab <- div(tab, onclick = "foo")
txt <- withTags(p(id = "mySelection"))
browsable(tagList(tab, txt))
```


```{js}
writeState = () => Reactable.onStateChange('myTable', state => {document.getElementById('mySelection').innerHTML = state.selected})
document.getElementById('myTable').onclick = writeState
```
0
Stéphane Laurent On

The doc says one can use htmlwidgets::onStaticRenderComplete or htmlwidgets::onRender.

tab <- reactable(dat, selection = "single", elementId = "myTable")
txt <- withTags(p(id = "mySelection"))
browsable(
  tagList(
    tab, 
    txt, 
    htmlwidgets::onStaticRenderComplete(
      "Reactable.onStateChange('myTable', state => {document.getElementById('mySelection').innerHTML = state.selected})"
    )
  )
)