Loop Inside React Jsx

Loop inside React JSX

Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go:

return tbody(
for (let i = 0; i < numrows; i++) {
ObjectRow()
}
)

See how the function tbody is being passed a for loop as an argument – leading to a syntax error.

But you can make an array, and then pass that in as an argument:

const rows = [];
for (let i = 0; i < numrows; i++) {
rows.push(ObjectRow());
}
return tbody(rows);

You can basically use the same structure when working with JSX:

const rows = [];
for (let i = 0; i < numrows; i++) {
// note: we are adding a key prop here to allow react to uniquely identify each
// element in this array. see: https://reactjs.org/docs/lists-and-keys.html
rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;

Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.

The for Loop inside React

You need to return the td's from the function you're writing in JSX and call the function as well like this:

return (
<div>
<table>
<tbody>
<tr>
{(() => {
let td = [];
for (let i = 1; i <= a; i++) {
td.push(<td key={i}>{i}</td>);
}
return td;
})()}
</tr>
</tbody>
</table>
</div>
);

A more efficient way to render it is to extract the function outside the JSX:

function daysInCurrentMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}

let a = daysInCurrentMonth();

const renderTD = () => {
let td = [];
for (let i = 1; i <= a; i++) {
td.push(<td key={i}>{i}</td>);
}
return td;
};

return (
<div>
<table>
<tbody>
<tr>{renderTD()}</tr>
</tbody>
</table>
</div>
);

If you want to remove the renderTD function you can create a new array of length a, but I guess it's not a very efficient method to do this.

function daysInCurrentMonth() {
var now = new Date();
return new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
}
let a = daysInCurrentMonth();

return (
<div>
<table>
<tbody>
<tr>
{[...Array(a).fill(0)].map((_, i) => (
<td key={i}>{i + 1}</td>
))}
</tr>
</tbody>
</table>
</div>
);

How to use For loop inside React JSX code

When interpolating JSX, you need to either return JSX, or have the expression evaluate to an array where each element of the array is JSX.

For a for loop to work, you'd have to push to an array, then return that array at the end.

If you want to do it all inside the interpolated JSX:

return (
<>
{(() => {
const arr = [];
for (let i = 0; i < count; i++) {
arr.push(
<div>
<h1>{i}</h1>
</div>
);
}
return arr;
})()}
</>
)

But a more readable approach is to return the array itself, without putting it inside a fragment:

const count = 10;
const arr = [];
for (let i = 0; i < count; i++) {
arr.push(
<div>
<h1>{i}</h1>
</div>
);
}
return arr;

But a for loop for this sort of situation is weird. The functional Array.from is better.

return Array.from(
{ length: 10 },
(_, i) => (
<div>
<h1>{i}</h1>
</div>
)
);

How do I use for loops with react?

The render method of your component, or your stateless component function, returns the elements to be rendered.

If you want to use a loop, that's fine:

render() {
let menuItems = [];
for (var i = 0; i < Users.length; i++) {
menuItems.push(<MenuItem eventKey=[i]>User.firstname[i]</MenuItem>);
}
return <div>{menuItems}</div>;
}

More common would be to see a more functional style, such as using a map to return the array of elements:

render() {
return <div>
{
Users.map((user, i) =>
<MenuItem eventKey=[i]>User.firstname[i]</MenuItem>)
}
</div>;
}

Note that in either case, you are missing the key property from each element of your array, so you will see warnings. Each element in an array should have a unique key, preferably some form of ID rather than just the array index.

Loop inside React JSX

Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go:

return tbody(
for (let i = 0; i < numrows; i++) {
ObjectRow()
}
)

See how the function tbody is being passed a for loop as an argument – leading to a syntax error.

But you can make an array, and then pass that in as an argument:

const rows = [];
for (let i = 0; i < numrows; i++) {
rows.push(ObjectRow());
}
return tbody(rows);

You can basically use the same structure when working with JSX:

const rows = [];
for (let i = 0; i < numrows; i++) {
// note: we are adding a key prop here to allow react to uniquely identify each
// element in this array. see: https://reactjs.org/docs/lists-and-keys.html
rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;

Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.

How to loop over a number in React inside JSX

You could use Array.from() instead.

let App = () => {

return <ul>{Array.from(Array(10), (e, i) => {

return <li key={i}>{i}</li>

})}</ul>

}

ReactDOM.render(

<App />,

document.getElementById('app')

);
<script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>

<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>

<div id="app"></div>

Loop inside of a loop, in React JSX

You forgot the wrapping div in your first map statement:

render() {
return (
<div>
{this.state.ans.map(item =>
<div> // this div was missing
{this.state.quest.map(quest => quest)}
{item}
</div>
)}
</div>
)
}

How to write for loop in JSX in React?

You can push the JSX to an array and render that.

class App extends React.Component {

render() {

const result = [];

for (var i = 0; i < 11; i++) {

result.push(<Print value={i} key={i} />);

}

return <div>{result}</div>;

}

}

const Print = props => {

return <div>{props.value}</div>;

};

ReactDOM.render(<App />, 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>

How to use if statement inside React JSX loop/map

You don't need to render conditionally. Use the condition inside the active property (and inside className if you need):

{breadCrumbData.BreadCrumbLinks.map(breadCrumbLink => 
(
<Breadcrumb.Item key={breadCrumbLink.Id} className="active" active={breadCrumbLink.IsActive}>
{breadCrumbLink.LinkText}
</Breadcrumb.Item>
)
)}


Related Topics



Leave a reply



Submit