Reputation: 1270
I'm trying to display a 2d array as a table, but I'm not entirely sure how would I go about this with React. This code currently only outputs the first row, I tried returning 2d arrays as a whole but that didn't work either.
var DisplayRow = React.createClass({
getDefaultProps: function() {
return {
columns: []
};
},
render: function(){
console.log(this.props.columns);
var entries = []
for (var i = 0; i < this.props.columns.length; i++){
return(
<DisplayElement row={this.props.columns[i]} key={i} />
);
};
}
});
var DisplayElement = React.createClass({
getDefaultProps: function(){
return {
row: []
};
},
render: function(){
console.log(this.props.row);
var elements = []
for (var i=0; i < this.props.row.length; i++){
elements.push(<td> {this.props.row[i]} </td>);
}
return (
<tr> {elements} </tr>
)
}
});
Upvotes: 1
Views: 9911
Reputation: 1270
Figured it out with much cleaner code:
var DisplayRow = React.createClass({
getDefaultProps: function(){
return {
columns: []
};
},
render: function(){
var rows = this.props.columns.map(function (item, i){
var entry = item.map(function (element, j) {
return (
<td key={j}> {element} </td>
);
});
return (
<tr key={i}> {entry} </tr>
);
});
return (
<table className="table-hover table-striped table-bordered">
<tbody>
{rows}
</tbody>
</table>
);
}
});
Upvotes: 4
Reputation: 4945
It could be something like this where SnipsView is the row and SnipsListItem are the columns.
class SnipListItemRender extends React.Component {
render() {
let snipSpanColor = (this.props.index === this.props.selectedKey) ? '#b58900' : '#afac87';
return (
<div id='SnipDivSty' onclick={this.snipClickHandler} className="FlexBox" style={SnipDivSty}>
<div id='SelectSnipDivSty' style={SelectSnipDivSty}>
<JButton btn={selectSnipBtn} parentClickHandler={this.snipClickHandler} />
</div>
<span id='SnipSpanSty' style={{color: snipSpanColor, width: 'calc(70% - 142px)'}}>{this.props.snippet.snip}</span>
<JButton btn={SnipBtn} parentClickHandler={this.snipClickHandler} />
</div>
);
}
}
class SnipListItem extends SnipListItemRender {
snipClickHandler = (buttonid) => { Actions.selectSnipItem(this.props.snippet, buttonid); }
}
let _snipDataMap = function(snip, index) {
return (
<li id='SnipsDivLiSty' key={index} style={SnipsDivLiSty}>
<SnipListItem snippet={snip} index={index} selectedKey={this.props.selectedKey} />
</li>
);
}
export default class SnipsView extends React.Component {
render() {
let list = this.props.data.map(_snipDataMap, this)
return (
<div id='SnipsDivSty' style={SnipsDivSty}>
<ul id='SnipsDivUlSty' style={SnipsDivUlSty}>
{list}
</ul>
</div>
);
}
}
Upvotes: 0