How to use Array.map( ) Method In ReactJS
In this approach, we are using Array.map() inside JSX to dynamically render a list of numbers from the state array numbers. Each number is displayed as an <li> element with inline styling for color, margin, and cursor. The approach1Fn function adds a random number to the list when the “Click Me” button is clicked, demonstrates dynamic rendering and user interaction within React JSX.
Syntax:
array.map((currentValue, index, array) => {
// code
}, thisArg);
Example: The below example uses Array.map() to Loop inside React JSX.
// App.js
import React, { useState } from 'react';
const App = () => {
const [numbers, setNumbers] =
useState([1, 2, 3, 4, 5]);
const approach1Fn = () => {
const randomNum =
Math.floor(Math.random() * 10) + 1;
setNumbers([...numbers, randomNum]);
};
return (
<div>
<h1 style={{ color: 'green' }}>
w3wiki
</h1>
<h3>Looping with Array.map()</h3>
<ul>
{numbers.map((number, index) => (
<li key={index}
style={{
marginBottom: '10px',
color: 'blue',
cursor: 'pointer'
}}>
Number {number}
</li>
))}
</ul>
<button onClick={approach1Fn}>
Click Me
</button>
</div>
);
};
export default App;
Output:
Loop Inside React JSX
When working with React, you often need to render lists of items dynamically. JavaScript’s map function provides a convenient way to loop through arrays and generate JSX elements for each item. In this article, we’ll explore how to loop inside JSX in React using various techniques and best practices.