render() doesn't called inside HOC component with passing children
Hi, I'm writing custom DataTable component and want to add support for rich cells. Example of desirable usage:
class TestTable extends Component {
render() {
return (
<DataTable>
<Column title="Rich Cell">
<FakeId/>
</Column>
<Column title="Name" dataField="name"/>
<Column title="Technolody" dataField="tech"/>
</DataTable>
)
}
}
<Column ../> is used to pass props only, during DataTable rendering it's replaced with header cells and body cells. To make rich cells working trying to save all children of Column and during rendering of cell inject actual rowData to them.
class DataTable extends PureComponent {
getColumnsDescription = (props: Props): ColumnsDescription =>
React.Children.map(props.children, (column, i) => {
return {
title: column.props.title,
dataField: column.props.dataField,
className: column.props.columnClassName,
width: column.props.width,
cellChildren: column.props.children,
index: i
}
}
);
}
HOC:
function withRowData(CellComponent: ClassComponent<*, *, *> | FunctionComponent<*, *>, data: DataEntry): ClassComponent<*, *, *> {
return class extends Component {
render() {
return <CellComponent
{...this.props}
rowData={data}
/>
}
}
}
Cell rendering
class TableCell extends PureComponent {
_renderRichCell() {
const {rowData, columnDescription} = this.props;
return React.Children.map(columnDescription.cellChildren, (cellComponent) => withRowData(cellComponent, rowData));
}
render() {
const {rowData, columnDescription} = this.props;
return (
<td>
{columnDescription.dataField && rowData[columnDescription.dataField]}
{!columnDescription.dataField && this._renderRichCell()}
</td>
)
}
}
The problem is that render() method of Column children (FakeId in example) doesn't called. In debugger result of _renderRichCell() looks ok (can provide snapshot if needed). No errors in console. Maybe it's not valid to use React.Children.map in TableCell to transform elements with another parent?
Have founded workaround for my case: use React.cloneElement instead of HOC. It works ok if no complicated logic, but only prop injecting needed.
React.Children.map(columnDescription.cellChildren,
(cellComponent) => React.cloneElement(cellComponent, {rowData}))
instead of
React.Children.map(columnDescription.cellChildren, (cellComponent) => withRowData(cellComponent, rowData))
This sounds right. HOCs produce components but you want elements. Creating new components in render() is extremely expensive and also destroys their state.