Movatterモバイル変換


[0]ホーム

URL:


Skip to contents

JavaScript API

Source:vignettes/javascript-api.Rmd
javascript-api.Rmd

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

Example: CSV download button

library(htmltools)htmltools::browsable(tagList(tags$button("Download as CSV", onclick="Reactable.downloadDataCSV('cars-table')"),reactable(MASS::Cars93[,1:5],      defaultPageSize=5,      elementId="cars-table")))

Using the JavaScript API

To use the JavaScript API, your table must first have a unique IDthat distinguishes it from other tables:

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.getDataCSV(  tableId:string,  options?: {    columnIds:string[],    headers:true,    sep:',',    dec:'.'  })

Value

A string with the table data in CSV format.

Examples

// Get table data as a CSV stringconst csv= Reactable.getDataCSV('cars-table')console.log(csv)// Get table data as a tab-separated values stringconst tsv= Reactable.getDataCSV('cars-table', {sep:'\t' })console.log(tsv)

Reactable.setSearch()

Sets the search value of a table. To clear the search, set the valuetoundefined.

Reactable.setSearch(  tableId:string,  value:any)

Examples

// Set the search value to "midsize"Reactable.setSearch('cars-table','midsize')// Clear the search valueReactable.setSearch('cars-table',undefined)

Reactable.setFilter()

Sets the filter value of a column. To clear the column filter, setthe value toundefined.

Reactable.setFilter(  tableId:string,  columnId:string,  value:any)

Examples

// Set the filter value of the "Type" column to "midsize"Reactable.setFilter('cars-table','Type','midsize')// Clear the filter value of the "Type" columnReactable.setFilter('cars-table','Type',undefined)

Reactable.setAllFilters()

Sets all column filter values in the table. To clear the columnfilters, setfilters to an empty array,[].

Reactable.setAllFilters(  tableId:string,  filters:Array<{ id:string, value:any }>)

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.toggleGroupBy(  tableId:string,  columnId:string,  isGrouped?:boolean)

Examples

// Toggle groupBy state for the "Type" columnReactable.toggleGroupBy('cars-table','Type')// Enable grouping for the "Type" columnReactable.toggleGroupBy('cars-table','Type',true)// Disable grouping for the "Type" columnReactable.toggleGroupBy('cars-table','Type',false)

Reactable.setGroupBy()

Sets thegroupBy columns for the table. To clear thegroupBy columns, setcolumnIds to an emptyarray,[].

Reactable.setGroupBy(  tableId:string,  columnIds:string[])

Examples

// Set the groupBy columns to "Type" and "Manufacturer"Reactable.setGroupBy('cars-table', ['Type','Manufacturer'])// Clear the groupBy columnsReactable.setGroupBy('cars-table', [])

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.toggleAllRowsExpanded(  tableId:string,  isExpanded?:boolean)

Examples

// Toggle expanded state for all rowsReactable.toggleAllRowsExpanded('cars-table')// Expand all rowsReactable.toggleAllRowsExpanded('cars-table',true)// Collapse all rowsReactable.toggleAllRowsExpanded('cars-table',false)

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.

Reactable.setMeta(  tableId:string,  meta?:object|Function)

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.toggleHideColumn(  tableId:string,  columnId:string,  isHidden?:boolean)

Examples

// Toggle hidden state for the "Type" columnReactable.toggleHideColumn('cars-table','Type')// Hide the "Type" columnReactable.toggleHideColumn('cars-table','Type',true)// Show the "Type" columnReactable.toggleHideColumn('cars-table','Type',false)

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,[].

Reactable.setHiddenColumns(  tableId:string,  columnIds:string[]|Function)

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.setData(  tableId:string,  data:Array<object>|object)

Examples

// Update data in row formatReactable.setData('cars-table', [  {Model:'Legend',Type:'Midsize' },  {Model:'Integra',Type:'Small' }])// Update data in column formatReactable.setData('cars-table', {Model: ['Legend','Integra'],Type: ['Midsize','Small']})

Reactable.getState()

Gets the current state of a table.

Reactable.getState(tableId:string)

Value

An object with the following properties:

PropertyExampleDescription
sorted[{ id: "Petal.Length", desc: true }, ...]columns being sorted in the table
page2page index (zero-based)
pageSize10page size
pages5number 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

Examples

Reactable.getState('cars-table')// { page: 2, searchValue: 'petal', ... }

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.

Reactable.onStateChange(  tableId:string,  listenerFn:Function)

Value

Reactable.onStateChange returns a function that can becalled to cancel the listener function.

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.

Reactable.gotoPage(  tableId:string,  pageIndex?:number|Function)

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)

Reactable.setPageSize()

New in v0.4.4.9000

Sets the current page size.

Reactable.gotoPage(  tableId:string,  pageSize?:number)

Examples

// Set the page size to 10Reactable.setPageSize('cars-table',10)

[8]ページ先頭

©2009-2025 Movatter.jp