From 56f49da1bb014c68ad25947b2c230b1db5c38694 Mon Sep 17 00:00:00 2001 From: Ricardo Hernandez-Montoya Date: Tue, 2 May 2017 11:38:48 +0200 Subject: [PATCH] Issue #56: tab jump in tables --- src/components/table.js | 70 +++++++++++++++++++++++++++++++---------- 1 file changed, 53 insertions(+), 17 deletions(-) diff --git a/src/components/table.js b/src/components/table.js index f0b94d1..f0798c5 100644 --- a/src/components/table.js +++ b/src/components/table.js @@ -29,6 +29,7 @@ class CustomTable extends Component { constructor(props) { super(props); + this.activeInput = null; this.state = { rows: [], editCell: [ -1, -1 ] @@ -125,6 +126,23 @@ class CustomTable extends Component { this.setState({ rows: rows }); } + componentDidUpdate() { + // A cell will not be selected at initial render, hence no need to call this in 'componentDidMount' + if (this.activeInput) { + this.activeInput.focus(); + } + } + + onCellFocus(index) { + // When a cell focus is detected, update the current state in order to uncover the input element + this.setState({ editCell: [ index.cell, index.row ]}); + } + + cellLostFocus() { + // Reset cell selection state + this.setState({ editCell: [ -1, -1 ] }); + } + render() { // get children var children = this.props.children; @@ -140,23 +158,41 @@ class CustomTable extends Component { - {this.state.rows.map((row, rowIndex) => ( - - {row.map((cell, cellIndex) => ( - this.onClick(event, rowIndex, cellIndex) : () => {}}> - {(this.state.editCell[0] === cellIndex && this.state.editCell[1] === rowIndex ) ? ( - children[cellIndex].props.onInlineChange(event, rowIndex, cellIndex)} /> - ) : ( - - {cell.map((element, elementIndex) => ( - {element} - ))} - - )} - - ))} - - ))} + { + this.state.rows.map((row, rowIndex) => ( + + { + row.map((cell, cellIndex) => { + + let isCellInlineEditable = children[cellIndex].props.inlineEditable === true; + + let tabIndex = isCellInlineEditable? 0 : -1; + + let evtHdls = isCellInlineEditable ? { + onCellClick: (event) => this.onClick(event, rowIndex, cellIndex), + onCellFocus: () => this.onCellFocus({cell: cellIndex, row: rowIndex}), + onCellBlur: () => this.cellLostFocus() + } : { + onCellClick: () => {}, + onCellFocus: () => {}, + onCellBlur: () => {} + }; + + return ( + {(this.state.editCell[0] === cellIndex && this.state.editCell[1] === rowIndex ) ? ( + children[cellIndex].props.onInlineChange(event, rowIndex, cellIndex)} inputRef={ref => { this.activeInput = ref; }} /> + ) : ( + + {cell.map((element, elementIndex) => ( + {element} + ))} + + )} + ) + }) + } + )) + } );