How do I iterate nested arrays in a React component?

19,108

Solution 1

One way to do it

var arr = [ [ 2, 3, 4, 5, 6, 7 ],
  [ 8, 9, 10, 11, 12, 13 ],
  [ 14, 15, 16, 17, 18, 19 ],
  [ 20, 21, 22, 23, 24, 25 ],
  [ 26, 27, 28, 29, 30, 31 ],
  [ 32, 33, 34, 35, 36, 37 ],
  [ 38, 39, 40, 41, 42, 43 ],
  [ 44, 45, 46, 47, 48, 49 ],
  [ 50, 51, 52, 53, 54, 55 ],
  [ 56, 57, 58, 59, 60, 61 ],
  [ 62, 63, 64, 65, 66, 67 ],
  [ 68, 69, 70, 71, 72, 73 ],
  [ 74, 75, 76, 77, 78, 79 ],
  [ 80, 81, 82, 83, 84, 85 ],
  [ 86, 87, 88, 89, 90, 91 ],
  [ 92, 93, 94, 95, 96, 97 ],
  [ 98, 99, 100, 101, 102, 103 ],
  [ 104, 105, 106, 107, 108, 109 ] ];

var Hello = React.createClass({
  tablerows: function() {
    return this.props.arr.map(rows => {
        var row = rows.map(cell => <td>{cell}</td>); 
        return <tr>{row}</tr>;
    });
  },
  render: function() {
    return <table>{this.tablerows()}</table>;
  }
});

ReactDOM.render(
  <Hello arr={arr} />,
  document.getElementById('container')
);

In action: https://jsfiddle.net/69z2wepo/30476/

Solution 2

I would suggest separating the components to Resultset, NumberComponent and try to be consistent with the arrow functions.

// Explicit return

const NumberComponent = props => {
    return (
        <td>{ props.number }</td>
    )
}

const Resultset = props => {
    return (
        <tr>
            {
                props.rows.map( number => <NumberComponent number={number} />)
            }
        </tr>
    )
}

// Implicit return

const NumberComponent = props => (<td>{ props.number }</td>);

const Resultset = props => (
    <tr>
        {
            props.rows.map( number => <NumberComponent number={number} />)
        }
    </tr>
);
Share:
19,108

Related videos on Youtube

GreenTriangle
Author by

GreenTriangle

Updated on June 04, 2022

Comments

  • GreenTriangle
    GreenTriangle about 2 years

    I have a multidimensional array: an array results containing 18 arrays row, each containing 6 numbers.

    I want to render this as a table. The logic would be

    results.each as (row)
         <tr>
             row.each as (number)
                   <td>number</td>
         </tr>
    

    But I can't figure out how you'd write this in JSX.

    const Resultset = props => (
        {props.rows.map(rows => {
            <tr>
                {rows.map(number => <td>{number}</td>)}
            </tr>
        })}
    );
    

    But that's not right. What's the procedure for this, how do you nest the map calls and interpolations?