Loops are important in programming because they can perform operations in seconds while shortening long lines of code. In this blog, we will learn the basics of Loops in React JSX and how they are used practically.
What is JSX?
JSX is just a JavaScript syntax extension and stands for XML JavaScript. We can write HTML code directly in React in JavaScript code. It's faster than regular JavaScript because it performs optimization while converting to regular JavaScript.
Sample JSX code
const handleButton = () => {
alert('Hello, Welcome to Loop Tutorial')
}
return(
<div>
<button onClick={() => handleButton()} title="submit">Click Me</button>
</div>
)
How to render loops in React JSX?
Loops in JSX offer a quick and easy way to do something over and over again. To address this, we'll look at 5 different forms of loops used to render elements in React JSX.
Map
You can iterate over an object using the map
method. You can use this method to render the same component repeatedly. Let's understand by an example.
import React from 'react'
const App = () => {
const users = ['Rahul', 'Shivam', 'Ayesha', 'Akash', 'Poonam'];
return(
<div>
<ul>
<li>
{ users.map((names, i) => {
return(
<li key={i}>{names}</li>
)
})}
</li>
</ul>
</div>
)
}
export defaultApp;
For
Users can use the standard for
loop to create the element. Here you should use the length
function to provide the last point of the loop.
import React from 'react'
const App = () => {
const users = [
{ id: 1, Name: 'Rahul' },
{ id: 2, Name: 'Shivam' },
{ id: 3, Name: 'Ayesha' },
{ id: 4, Name: 'Akash' },
{ id: 5, Name: 'Poonam' }
];
const displayUser = (users) => {
let name = [];
for (let i = 0; i < users.length; i++) {
name.push(<li key={users[i].id}>{users[i].Name}</li>);
}
return name;
}
return(
<div>
<ul>
{displayUser(users)}
</ul>
</div>
)
}
export default App;
forEach
The forEach
method is used to run a function on each array element.
import React from 'react'
const App = () => {
const users = [
{ id: 1, Name: 'Rahul' },
{ id: 2, Name: 'Shivam' },
{ id: 3, Name: 'Ayesha' },
{ id: 4, Name: 'Akash' },
{ id: 5, Name: 'Poonam' }
];
const name = [];
users.forEach((user) => {
name.push(<li key={user.id}>{user.Name}</li>);
});
return(
<div>
See more at: https://tablognews.netlify.app/posts/post/loops-em-react-jsx-um-mergulho-profundo-no-basico
Top comments (0)