Introduction
The JavaScript API lets you manipulate and access tables fromJavaScript. You can use this to create custom interactive controls foryour table without the use of Shiny, or add cross-widget interactionsbeyond what Crosstalk provides.
Common use cases for the JavaScript API include:
- Export buttons to download table data to a CSV file
- Custom filter inputs located outside of the table
- Toggle buttons for row grouping or row expansion
Using the JavaScript API
To use the JavaScript API, your table must first have a unique IDthat distinguishes it from other tables:
For tables in static documents (e.g., R Markdown), add an IDthrough the
elementIdargument inreactable():For tables in Shiny apps, the ID will be the Shiny output IDspecified in
reactableOutput(). For example, the table inthis app usescars_tableas its ID:library(shiny)ui<-fluidPage(reactableOutput("cars_table"))server<-function(input,output){output$cars_table<-renderReactable({reactable(MASS::Cars93)})}shinyApp(ui,server)
Once your table has an ID, you can use any of theReactable JavaScript functions with that table ID. Forexample, to download data from thecars-table table to aCSV file, the JavaScript code would look like this:
// Download the "cars-table" data to a CSV file named 'cars.csv'Reactable.downloadDataCSV('cars-table','cars.csv')To try this out interactively, you can open yourbrowser’sdeveloper tools and run this function in theJavaScriptconsole.
Creating custom interactive controls
Most users will likely want to use the JavaScript API through aninteractive control, such as a button, so they could decide when todownload the table data. Using HTML, you can create a<button> element with anonclick actionthat calls theReactable JavaScript function.
This example uses thehtmltools package to render a CSVdownload button. You can copy this code into an R console to view theoutput:
library(htmltools)htmltools::browsable(tagList(tags$button("Download as CSV", onclick="Reactable.downloadDataCSV('cars-table', 'cars.csv')"),reactable(MASS::Cars93[,1:5], elementId="cars-table")))Note:htmltools::browsable() is aconvenient way to view the rendered HTML when copying code into theconsole. It isn’t required to render HTML in R Markdown documents orShiny apps.
To reuse this button in other tables, you can also convert it into afunction that generates download buttons:
library(htmltools)csvDownloadButton<-function(tableId,label="Download as CSV",filename="data.csv"){htmltools::tags$button(label, onclick=sprintf("Reactable.downloadDataCSV('%s', '%s')",tableId,filename))}htmltools::browsable(tagList(csvDownloadButton("cars-table","Download as CSV", filename="cars.csv"),reactable(MASS::Cars93[,1:5], elementId="cars-table")))For more examples of custom controls that use the JavaScript API,check out theJavaScript APIexamples.
JavaScript API Reference
Reactable.downloadDataCSV()
Downloads the table data to a CSV file. The downloaded file will benameddata.csv by default, but you can customize this usingthe optionalfilename argument.
The downloaded data will include any filters that have been applied,and exclude any sorting or grouping. Hidden columns will also beincluded, but this may be customizable in the future.
For further customization, you can use theoptionsargument to only include specific columns, exclude column headers,change the field separator, or change the decimal separator (new inv0.4.0).
Reactable.downloadDataCSV( tableId:string, filename="data.csv",// New in v0.4.0 options?: { columnIds:string[], headers:true, sep:',', dec:'.' })Examples
// Download table data to a file named data.csvReactable.downloadDataCSV('cars-table')// Download table data to a file named cars93.csvReactable.downloadDataCSV('cars-table','cars93.csv')// Download table data to a tab-separated values fileReactable.downloadDataCSV('cars-table','cars93.tsv', {sep:'\t' })// Download table data with custom columns and headers excludedReactable.downloadDataCSV('cars-table','cars93.csv', {columnIds: ['Model','Type'],headers:false})Reactable.getDataCSV()
New in v0.4.0
Gets the table data as a CSV string. Same asReactable.downloadDataCSV()but does not download the data.
Reactable.setSearch()
Sets the search value of a table. To clear the search, set the valuetoundefined.
Reactable.setFilter()
Sets the filter value of a column. To clear the column filter, setthe value toundefined.
Reactable.setAllFilters()
Sets all column filter values in the table. To clear the columnfilters, setfilters to an empty array,[].
Examples
// Set the column filters for the "Type" columnReactable.setAllFilters('cars-table', [{id:'Type',value:'midsize' }])// Set the column filters for the "Type" and "Model" columnsReactable.setAllFilters('cars-table', [ {id:'Type',value:'midsize' }, {id:'Model',value:'legend' }])// Clear all column filtersReactable.setAllFilters([])Reactable.toggleGroupBy()
Toggles thegroupBy state for a column between groupedand ungrouped. To enable or disable grouping explicitly, set theoptionalisGrouped argument totrue orfalse.
Reactable.setGroupBy()
Sets thegroupBy columns for the table. To clear thegroupBy columns, setcolumnIds to an emptyarray,[].
Reactable.toggleAllRowsExpanded()
Toggles the expanded state of all rows in the table between expandedand collapsed. To expand or collapse rows explicitly, set the optionalisExpanded argument totrue orfalse.
Reactable.setMeta()
New in v0.4.0
Sets the custom metadata for the table.meta can eitherbe an object with new values, or a function that takes the previousmetadata object and returns new values.
New values are merged into the current metadata, so only the valuesspecified inmeta will be updated. To clear all metadata,setmeta toundefined.
Examples
// Set metadata, updating the values for the `count`, `enabled`, and `formatter` propertiesReactable.setMeta('cars-table', {count:123,enabled:true,formatter: value=>'$'+ value })// Set metadata using a function that increments `count` and toggles an `enabled` booleanReactable.setMeta('cars-table', prevMeta=> {return {count: prevMeta.count+1,enabled:!prevMeta.enabled }})// Clear metadataReactable.setMeta('cars-table',undefined)Reactable.toggleHideColumn()
New in v0.4.0
Toggles the hidden state for a column between hidden and shown. Tohide or show a column explicitly, set the optionalisHiddenargument totrue orfalse.
Reactable.setHiddenColumns()
New in v0.4.0
Sets the hidden columns for the table.columnIds caneither be an array of column IDs, or a function that takes the previoushidden column IDs and returns new column IDs.
To clear the hidden columns, setcolumnIds to an emptyarray,[].
Examples
// Set the hidden columns to "Type" and "Manufacturer"Reactable.setHiddenColumns('cars-table', ['Type','Manufacturer'])// Set hidden columns using a function that adds "Type" to the existing hidden columnsReactable.setHiddenColumns('cars-table', prevHiddenColumns=> {return prevHiddenColumns.concat('Type')})// Clear the hidden columnsReactable.setHiddenColumns('cars-table', [])Reactable.setData()
New in v0.4.0
Updates the table data.data can either be in row orcolumn format. In row format,data is an array of rowobjects. In column format,data is an object containingarrays of column values.data should have all the samecolumns as the original table data.
When updating data, the selected rows and current page will reset bydefault. All other state will persist, including sorting, filtering, andgrouping state.
Reactable.getState()
Gets the current state of a table.
Value
An object with the following properties:
| Property | Example | Description |
|---|---|---|
sorted | [{ id: "Petal.Length", desc: true }, ...] | columns being sorted in the table |
page | 2 | page index (zero-based) |
pageSize | 10 | page size |
pages | 5 | number of pages |
filters | [{ id: "Species", value: "petal" }] | column filter values |
searchValue | "petal" | table search value |
selected | [0, 1, 4] | selected row indices (zero-based) |
pageRows | [{ Petal.Length: 1.7, Species: "setosa" }, ...] | current row data on the page |
sortedData | [{ Petal.Length: 1.7, Species: "setosa" }, ...] | current row data in the table (after sorting, filtering, grouping) |
data | [{ Petal.Length: 1.7, Species: "setosa" }, ...] | original row data in the table |
meta | { custom: 123 } | custom table metadata fromreactable()(new in v0.4.0) |
hiddenColumns | ["Petal.Length"] | columns being hidden in the table |
Reactable.onStateChange()
New in v0.4.0
Sets up a function that will be called whenever the table statechanges.
listenerFn should be a function that takes the currenttable state, an object with properties described atstate properties.
Reactable.onStateChange() can only be run when the tablehas finished rendering, which isn’t guaranteed to happen at page loadtime. To ensure that the table is ready before runningReactable.onStateChange(), you can either usehtmlwidgets::onRender() for static widgets and Shinyoutputs, orhtmlwidgets::onStaticRenderComplete() forstatic widgets only.
Examples
Reactable.onStateChange('cars-table', state=> {console.log('selected rows:', state.selected)})// Cancel the listener functionconst cancel= Reactable.onStateChange('cars-table', listenerFn)cancel()Static widgets
library(htmltools)data<-MASS::Cars93[,c("Manufacturer","Model","Type","Price")]browsable(tagList("Table state:",tags$pre(id="tbl-state","{}"),reactable(data, searchable=TRUE, selection="multiple", onClick="select", elementId="tbl"),htmlwidgets::onStaticRenderComplete(" Reactable.onStateChange('tbl', state => { const { selected, sorted, searchValue, pageIndex } = state document.getElementById('tbl-state').textContent = JSON.stringify({ selected, sorted, searchValue, pageIndex }) }) ")))Shiny outputs
library(shiny)data<-MASS::Cars93[,c("Manufacturer","Model","Type","Price")]ui<-fluidPage(reactableOutput("tbl"),verbatimTextOutput("tbl_state"))server<-function(input,output){output$tbl<-renderReactable({tbl<-reactable(data, searchable=TRUE)htmlwidgets::onRender(tbl,"() => { Reactable.onStateChange('tbl', state => { const { sorted, searchValue } = state Shiny.setInputValue('tbl_state', { sorted, searchValue }) }) }")})output$tbl_state<-renderPrint({writeLines("Table state:\n")print(input$tbl_state)})}shinyApp(ui,server)Reactable.gotoPage()
New in v0.4.4.9000
Changes the current page.pageIndex can either be anumber or a function that takes the previouspageIndex andreturns the new value.
pageIndex is zero-based, so the first page would have apageIndex of0. IfpageIndex isoutside the validpageIndex range,Reactable.gotoPage() will do nothing.
Examples
// Go to page index 0 (the first page)Reactable.gotoPage('cars-table',0)// Go to page index 2 (the third page)Reactable.gotoPage('cars-table',2)// Go to the next pageReactable.gotoPage('cars-table', prevPage=> prevPage+1)// Go to the previous pageReactable.gotoPage('cars-table', prevPage=> prevPage-1)