react-toolbox/components/table/TableRow.js

86 lines
2.4 KiB
JavaScript
Raw Normal View History

2015-11-14 12:26:50 +03:00
import React from 'react';
2015-11-28 22:17:55 +03:00
import ClassNames from 'classnames';
2015-11-14 12:26:50 +03:00
import Checkbox from '../checkbox';
import utils from '../utils/utils';
2015-11-14 12:26:50 +03:00
import style from './style';
class TableRow extends React.Component {
static propTypes = {
data: React.PropTypes.object,
index: React.PropTypes.number,
model: React.PropTypes.object,
2015-11-14 12:26:50 +03:00
onChange: React.PropTypes.func,
onSelect: React.PropTypes.func,
selectable: React.PropTypes.bool,
2015-11-14 12:26:50 +03:00
selected: React.PropTypes.bool
};
handleInputChange = (index, key, type, event) => {
2015-11-14 12:26:50 +03:00
const value = type === 'checkbox' ? event.target.checked : event.target.value;
const onChange = this.props.model[key].onChange || this.props.onChange;
onChange(index, key, value);
2015-11-14 12:26:50 +03:00
};
renderSelectCell () {
if (this.props.selectable) {
2015-11-14 12:26:50 +03:00
return (
<td className={style.selectable}>
<Checkbox checked={this.props.selected} onChange={this.props.onSelect} />
</td>
);
}
}
renderCells () {
return Object.keys(this.props.model).map((key) => {
return <td key={key}>{this.renderCell(key)}</td>;
});
}
renderCell (key) {
const value = this.props.data[key];
// if the value is a valid React element return it directly, since it
// cannot be edited and should not be converted to a string...
if (React.isValidElement(value)) { return value; }
const onChange = this.props.model[key].onChange || this.props.onChange;
if (onChange) {
2015-11-14 12:26:50 +03:00
return this.renderInput(key, value);
} else if (value) {
return value.toString();
}
}
renderInput (key, value) {
const index = this.props.index;
2015-11-14 12:26:50 +03:00
const inputType = utils.inputTypeForPrototype(this.props.model[key].type);
const inputValue = utils.prepareValueForInput(value, inputType);
const checked = inputType === 'checkbox' && value ? true : null;
return (
<input
checked={checked}
onChange={this.handleInputChange.bind(null, index, key, inputType)}
2015-11-14 12:26:50 +03:00
type={inputType}
value={inputValue}
/>
);
}
render () {
2015-11-28 22:17:55 +03:00
const className = ClassNames(style.row, {
[style.editable]: this.props.onChange,
[style.selected]: this.props.selected
});
2015-11-14 12:26:50 +03:00
return (
<tr data-react-toolbox-table='row' className={className}>
{this.renderSelectCell()}
{this.renderCells()}
2015-11-14 12:26:50 +03:00
</tr>
);
}
}
export default TableRow;