chrisdew chrisdew - 1 month ago 11
Javascript Question

How to render repeating elements?

I've written some code to render repeating elements in ReactJS, but I hate how ugly it is.

render: function(){
var titles = this.props.titles.map(function(title) {
return <th>{title}</th>;
});
var rows = this.props.rows.map(function(row) {
var cells = [];
for (var i in row) {
cells.push(<td>{row[i]}</td>);
}
return <tr>{cells}</tr>;
});
return (
<table className="MyClassName">
<thead>
<tr>{titles}</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}


Is there a better way to achieve this?

(I would like to embed
for
loops within the template code, or some similar approach.)

Answer

You can put expressions inside curly brackets. Notice in the compiled JavaScript why a for loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.

(Also: Remember to add key attributes to components rendered inside loops.)

JSX:

render: function() {
  return (
    <table className="MyClassName">
      <thead>
        <tr>
          {this.props.titles.map(function(title) {
            return <th key={title}>{title}</th>;
          })}
        </tr>
      </thead>
      <tbody>
        {this.props.rows.map(function(row, i) {
          return (
            <tr key={i}>
              {row.map(function(col, j) {
                return <td key={j}>{col}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
} 

JavaScript:

render: function() {
  return (
    React.DOM.table({className: "MyClassName"}, 
      React.DOM.thead(null, 
        React.DOM.tr(null, 
          this.props.titles.map(function(title) {
            return React.DOM.th({key: title}, title);
          })
        )
      ), 
      React.DOM.tbody(null, 
        this.props.rows.map(function(row, i) {
          return (
            React.DOM.tr({key: i}, 
              row.map(function(col, j) {
                return React.DOM.td({key: j}, col);
              })
            )
          );
        })
      )
    )
  );
} 
Comments