Sunday, October 14, 2018

ReactJS: Embedded expression rendering as array instead of individual elements


User, im1dermike, wants to know why an embedded ReactJS expression is rendering as an array instead of individual elements


He has the following nested components:

<Table data={records}>
    <TableColumn field="code">Code</TableColumn>
    {columns.map((column, i) => (
      <TableColumn key={column} field={column}>
        {column}
      </TableColumn>
    ))}
</Table>



StackOverflow user, Donovan Hiland, answer:

Your JSX compiles down to something that looks like this:
const TableColumn = React.createElement('div', { field: 'code' }, 'Code')
const Table = React.createElement('div', {}, [
  TableColumn,
  columns.map((column, i) =>
    React.createElement('div', { key: column, field: column }, column),
  ),
])
You can see the children of Table include a react element, and an array of react elements. Iterating over the children array directly will give you just that.
React provides a top level api for this kind of thing -- React.Children -- which traverses child arrays in your iterations with React.Children.map and React.Children.forEach.
The adjusted function would look like:
getDefaultSortColumn() {
  let col = this.props.children[0].props.field;
  React.Children.forEach(this.props.children, (column) => {
    if (column.props.sortDefault) {
      col = column.props.field;
    }
  });
  return col;
}

im1dermike follow up question: 

That results in the following error:
Argument of type '(column: ReactElement<any>) => void' is not assignable to parameter of type '(child: ReactChild, index: number) => any'. Types of parameters 'column' and 'child' are incompatible. Type 'ReactChild' is not assignable to type 'ReactElement<any>'. Type 'string' is not assignable to type 'ReactElement<any>'

Donovan Hiland answer

Type checking aside, the answer is still valid and is the preferred/recommended method for looping over children in React without having to check for nested arrays. I'll update the answer to exclude the type checking bit and let you figure that part out. 

See here for example: codesandbox.io/s/jvxqvw3813



https://stackoverflow.com/users/7165303/donovan-hiland

No comments:

Post a Comment