M
M
monochromer2018-08-19 14:09:26
React
monochromer, 2018-08-19 14:09:26

How to extract information from children in React?

Hello!
There is such an API for setting table settings:

<Grid>
  <Column field="ProductID" />
  <Column field="ProductName" />
  <GridToolbar>
    <button onClick={this.saveToPDF}>save to pdf</button>
    <button onClick={this.saveToXLS}>save to xls</button>
  </GridToolbar>
</Grid>

Here, child components are used not for direct rendering, but for setting table settings - which fields to display from the data array, column widths, etc. There is also a toolbar, where there are, for example, buttons for exporting data.
Actually the question is how, when filtering children, to understand which element is Column , which GridToolbar , etc.? Are there any good practices for this? I lean towards checking the property type.namewhich is supposed to be the name of the component, i.e. 'Column', 'GridToolbar' etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-19
@monochromer

We used a similar technique, but with a different purpose. We passed all the steps of any process as children to the form widget and rendered only the current one.
What you want to do can be done like this:

class Grid extends React.Component {
  getContent() {
    const { children } = this.props;

    if (!children) return null;

    return React.Children.map(children, (child, index) => {  // или forEach без return, в зависимости от целей
      const { displayName } = child.type;

      switch (displayName) {
        case 'Column':
          // do something
        default:
          // do something other
      }
    });
  }

  render () {
    return (
      <Wrapper>
       {this.getContent()}
      </Wrapper>
    )
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question