Reputation: 5804
My objective is to create the following html table from a list of rows ([1, 2, 3]) and a list of columns ([1, 2]) using ReactJS:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
See below for my React script and here for my codepen, which doesnt seem to be working
class Tbody extends React.Component {
constructor(props) {
super(props);
this.state = {
columns: [1, 2],
rows: [1, 2, 3]
};
}
renderCols() {
return (
{this.state.columns.map(col => <td key={col}> {col} </td>)}
);
}
renderRows(){
return (
{this.state.rows.map(row => <tr key={row}> {this.renderCols()} </tr>)}
);
}
render() {
return <tbody>{this.renderRows()}</tbody>;
}
}
class Table extends React.Component {
render() {
return (
<div>
<table>
<Tbody />
</table>
</div>
);
}
}
ReactDOM.render(<Table />, document.getElementById("root"));
Upvotes: 1
Views: 1598
Reputation: 118261
Your renderCols
and renderRows
method returning the JSX. Instead return from there just plain JS objects, remove those {..}
.
class Tbody extends React.Component {
constructor(props) {
super(props);
this.state = {
cols: [1, 2],
rows: [1, 2, 3]
};
}
renderCols() {
return (
this.state.cols.map(col => <td key={col}>{col}</td>)
);
};
renderRows(){
return (
this.state.rows.map(row => <tr key={row}>{this.renderCols()}</tr>)
);
}
render() {
return <tbody>{this.renderRows()}</tbody>;
}
}
class Table extends React.Component {
render() {
return (
<div>
<table>
<Tbody />
</table>
</div>
);
}
}
ReactDOM.render(<Table />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 3