Skip to content

Repository files navigation

build statusbitHound Scorecodecov

reactabular-easy - Easy, opinionated wrapper for Reactabular

Given Reactabular is flexible by design, it's not the easiest to use and you may have to do quite a bit of wiring to make it work the way you want. reactabular-easy has been designed to make using it easier. It is opinionated and takes away some power. But on the plus side it allows you to render a fully featured table faster.

How to Use?

To make the drag and drop functionality work, you have to set up react-dnd-html5-backend or some other React DnD backend.

You can find suggested default styling for the package at style.css in the package root.

If you want to use the drag and drop functionality, you have to set up React DnD!

/*import React from 'react';import * as resolve from 'table-resolver';import * as dnd from 'reactabular-dnd';import * as easy from 'reactabular-easy';import VisibilityToggles from 'react-visibility-toggles';import * as resizable from 'reactabular-resizable';import * as tree from 'treetabular';import * as search from 'searchtabular';import HTML5Backend from 'react-dnd-html5-backend';import { DragDropContext } from 'react-dnd';import { compose } from 'redux';import uuid from 'uuid';import cloneDeep from 'lodash/cloneDeep';import findIndex from 'lodash/findIndex';import { generateParents, generateRows} from './helpers';*/constschema={type: 'object',properties: {Id: {type: 'string'},fullName: {$ref: '#/definitions/fullName'},company: {type: 'string'},age: {type: 'integer'},boss: {$ref: '#/definitions/boss'}},required: ['Id','fullName','company','age','boss'],definitions: {boss: {type: 'object',properties: {name: {type: 'string'}},required: ['name']},fullName: {type: 'object',properties: {first: {type: 'string'},last: {type: 'string'}},required: ['first','last']}}};constrows=generateParents(generateRows(200,schema),'Id');classEasyDemoextendsReact.Component{constructor(props){super(props);this.state={
rows,columns: this.getColumns(),sortingColumns: {},query: {},hiddenColumns: {}// <id>: <hidden> - show all by default};this.table=null;this.onMoveRow=this.onMoveRow.bind(this);this.onDragColumn=this.onDragColumn.bind(this);this.onMoveColumns=this.onMoveColumns.bind(this);this.onToggleColumn=this.onToggleColumn.bind(this);this.onSelectRow=this.onSelectRow.bind(this);this.onRemove=this.onRemove.bind(this);this.onSort=this.onSort.bind(this);this.onToggleShowingChildren=this.onToggleShowingChildren.bind(this);}componentWillMount(){this.resizableHelper=resizable.helper({globalId: uuid.v4(),getId: ({ id })=>id});}componentWillUnmount(){this.resizableHelper.cleanup();}getColumns(){return[{id: 'demo',// Unique ids for handling visibility checksheader: {label: 'Demo',draggable: true,resizable: true,formatters: [()=><span>Testing</span>]},cell: {formatters: [()=><span>Demo</span>,],toggleChildren: true},width: 100},{id: 'name',header: {label: 'Name'// Disabled for now as this is a difficult case in React DnD//draggable: true},children: [{id: 'firstName',property: 'fullName.first',header: {label: 'First Name',draggable: true,sortable: true,resizable: true},cell: {highlight: true},width: 125},{id: 'lastName',property: 'fullName.last',header: {label: 'Last Name',draggable: true,sortable: true,resizable: true},cell: {highlight: true},width: 125}]},{id: 'age',property: 'age',header: {label: 'Age',draggable: true,sortable: true,resizable: true},cell: {highlight: true},width: 150},{id: 'company',property: 'company',header: {label: 'Company',draggable: true,sortable: true,resizable: true},cell: {highlight: true},width: 250},{id: 'bossName',property: 'boss.name',header: {label: 'Boss',draggable: true,sortable: true,resizable: true},cell: {highlight: true},width: 200},{cell: {formatters: [(value,{ rowData })=>(<div><inputtype="button"value="Click me"onClick={()=>alert(`${JSON.stringify(rowData,null,2)}`)}/><spanclassName="remove"onClick={()=>this.onRemove(rowData.Id)}style={{marginLeft: '1em',cursor: 'pointer'}}>
&#10007;
</span></div>)]},width: 200}];}render(){const{
searchColumn, columns, sortingColumns, rows, query, hiddenColumns
}=this.state;constidField='Id';constparentField='parent';constvisibleColumns=compose(// 5. Patch columns with classNames for resizingthis.resizableHelper.initialize,// 4. Bind columns (extra functionality)easy.bindColumns({toggleChildrenProps: {className: 'toggle-children'},
sortingColumns,
rows,
idField,
parentField,props: this.props,// HandlersonMoveColumns: this.onMoveColumns,onSort: this.onSort,onDragColumnStart: (width,extra)=>console.log('drag column start',width,extra),onDragColumn: this.onDragColumn,onDragColumnEnd: (width,extra)=>console.log('drag column end',width,extra),onToggleShowingChildren: this.onToggleShowingChildren}),// 3. Filter based on visibility again (children level)columns=>columns.filter(column=>!hiddenColumns[column.id]),// 2. Unpacktree.unpack(),// 1. Filter based on visibility (root level)columns=>columns.filter(column=>!hiddenColumns[column.id]))(columns);constcolumnChildren=visibleColumns.filter(column=>!column._isParent);constheaderRows=resolve.headerRows({columns: tree.pack()(visibleColumns)});return(<div><VisibilityTogglescolumns={tree.unpack()(columns)}onToggleColumn={this.onToggleColumn}isVisible={({column: { id }})=>!hiddenColumns[id]}/><divclassName="scroll-container"><label>Scroll to index: </label><div><inputtype="text"onChange={e=>this.table.tableBody.scrollTo(e.target.value)}/></div></div><divclassName="search-container"><span>Search</span><search.Fieldcolumn={searchColumn}query={query}columns={columnChildren}rows={rows}onColumnChange={searchColumn=>this.setState({ searchColumn })}onChange={query=>this.setState({ query })}/></div><easy.Tableref={table=>{this.table=table}}rows={rows}headerRows={headerRows}rowKey="Id"sortingColumns={sortingColumns}tableWidth={800}tableHeight={400}columns={columnChildren}query={query}classNames={{table: {wrapper: 'pure-table pure-table-striped'}}}headerExtra={<search.Columnsquery={query}columns={columnChildren}onChange={query=>this.setState({ query })}/>}idField={idField}parentField={parentField}onMoveRow={this.onMoveRow}onSelectRow={this.onSelectRow}/></div>);}onMoveRow({ sourceRowId, targetRowId }){constrows=tree.moveRows({operation: dnd.moveRows({
sourceRowId,
targetRowId,idField: 'Id'}),idField: 'Id',// Defaults to idparentField: 'parent'})(this.state.rows);rows&&this.setState({ rows });}onDragColumn(width,{ column }){this.resizableHelper.update({
column,
width
});}onMoveColumns({ sourceLabel, targetLabel }){constcolumns=tree.unpack()(this.state.columns);constsourceIndex=findIndex(columns,{header: {label: sourceLabel}});consttargetIndex=findIndex(columns,{header: {label: targetLabel}});if(sourceIndex<0||targetIndex<0){returnnull;}letsource=columns[sourceIndex];lettarget=columns[targetIndex];if(source._isParent){returnconsole.warn('Dragging parents is not supported yet');}// If source doesn't have a parent, make sure we are dragging to// target parent by modifying the original structure.if(!source.parent){consttargetParents=tree.getParents({index: findIndex(columns,{id: target.id})})(columns);// If trying to drag to a child, drag to its root// parent instead.if(targetParents.length){returnconsole.warn('Dragging to a nested column is not supported yet');}constnestedSourceIndex=findIndex(this.state.columns,{header: {label: sourceLabel}});source=this.state.columns[nestedSourceIndex];constnestedTargetIndex=findIndex(this.state.columns,{header: {label: target.header.label}});target=this.state.columns[nestedTargetIndex];if(nestedSourceIndex<0||nestedTargetIndex<0){returnnull;}// We are operating at root level now so move accordingly.constmovedColumns=dnd.move(this.state.columns,nestedSourceIndex,nestedTargetIndex);// Retain widths while movingmovedColumns[nestedSourceIndex].width=source.width;movedColumns[nestedTargetIndex].width=target.width;this.setState({columns: movedColumns});}elseif(source.parent===target.parent){// Dragging within children now. This has to be against flattened data.constmovedColumns=dnd.move(columns,sourceIndex,targetIndex);// Retain widths while moving.// XXX: This works only for single level nesting.constsourceWidth=source.width;consttargetWidth=target.width;source.width=targetWidth;target.width=sourceWidth;this.setState({columns: tree.pack()(movedColumns)});}// If trying to drag from children to other children or so, do nothing.}onSelectRow({ selectedRowId, selectedRow }){console.log('onSelectRow',selectedRowId,selectedRow);}onSort(sortingColumns){console.log('onSort',sortingColumns);this.setState({ sortingColumns });}onToggleColumn({ column }){const{ hiddenColumns }=this.state;this.setState({hiddenColumns: {
...hiddenColumns,[column.id]: !hiddenColumns[column.id]}});}onRemove(id){constrows=cloneDeep(this.state.rows);constidx=findIndex(rows,{ Id });// this could go through flux etc.rows.splice(idx,1);this.setState({ rows });}onToggleShowingChildren(rowIndex){constrows=cloneDeep(this.state.rows);rows[rowIndex].showingChildren=!rows[rowIndex].showingChildren;this.setState({ rows });//},}}// Set up drag and drop context// const DragAndDropDemo = DragDropContext(HTML5Backend)(EasyDemo);<EasyDemo/>/*export default EasyDemo*/

Styling

It is possible to pass custom classNames and props as listed below:

classNames: {table: null,header: {wrapper: null// TODO/* row: null, cell: null */},body: {wrapper: null// TODO/* row: null, cell: null */}},props: {resize: {container: {style: {color: 'red'}},value: {},handle: {}},sort: {container: {},value: {},order: {}}}

For more control, you can also override components and also inject styling and class names through the column definition and the onRow handler.

Customization

If you want to customize resize/sort controls further (add classNames etc.), pass props like this:

props: {resize: {container: {},value: {},handle: {}},sort: {container: {},value: {},order: {}}},

License

MIT.

About

Easy, opinionated wrapper for Reactabular (MIT)

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages