I have a JSX like:
<table>
<thead> value </thead>
<tr> values </tr>
</table>
How can I iterate <tr>
alone for 10 times?
I have a JSX like:
<table>
<thead> value </thead>
<tr> values </tr>
</table>
How can I iterate <tr>
alone for 10 times?
This is the es6 version of the answer.
render () {
const values = [1, 2, 3, 4, 5];
return (
<table>
<thead></thead>
{values.map((item) => {
return (
<tr key={item}>
<td>{item}</td>
</tr>
);
})}
</table>
);
}
A simple for
loop will do:
renderTableRow() {
let trs = []
for(let i = 0; i < 10; i++) {
trs.push((<tr>{this.props.listOfItems[i]}</tr>))
}
return trs
}
in the table it can look like this:
<table>
<thead></thead>
{this.renderTableRow()}
</table>
I understand you asked this question not too long ago and was given this link, looping inside JSX. Make sure you check it out if you need more information.
React allows you to run JavaScript functions within your JSX using curly braces. You can either write a JavaScript function in which you're returning an array of <tr>
(which JSX will render correctly). Or, probably more preferably, you can hold the values you want to display within an array and use a map()
function within your JSX. For example:
render() {
const values = [1, 2, 3, 4, 5];
return (
<table>
<thead></thead>
{values.map(function(currValue){
return (
<tr key={currValue}>
<td>{currValue}</td>
</tr>
);
})}
</table>
);
}
There are several examples you can find accomplishing running a loop in JSX, such as: loop inside React JSX