0
\$\begingroup\$

How can I make this code block shorter? I'm repeating myself, because of this prop cellRenderer.

{headers.map((header, i) => {
  return header.index ? (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
      cellRenderer={this._generateCheckbox}
    />
  ) : (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
    />
  );
})}
\$\endgroup\$
2
\$\begingroup\$

Passing undefined in for cellRenderer should be the same as not passing it in at all. Because of this, the duplication can be removed by doing the following:

{headers.map((header, i) => {
  return (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
      cellRenderer={header.index ? this._generateCheckbox : undefined}
    />
  )
})}

Alternatively, you can build up an extraProps object and then spread it into the column.

{headers.map((header, i) => {
  let extraProps = header.index ? {
    cellRenderer: this._generateCheckbox
  } : {}
  return (
    <Column
      label={header.label}
      dataKey={header.id}
      disableSort
      width={100}
      flexGrow={1}
      {...extraProps}
    />
  )
})}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.