Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping <li> elements in JSX React

In React.js documentation, I wonder how Array.map() is used in JSX React.

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>
      {number}
    </li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

in <ul> tag, why we just put the variable listItems directly?. Because I think it will return a single array instead of <li> elements like this :

<ul>
[
<li></li>,
<li></li>,
<li></li>,
]
</ul>

how does JSX treat an array? Did I have to loop listItems manually?

Thank you in advance.

like image 928
Fiqih Alfito Avatar asked Jul 17 '26 07:07

Fiqih Alfito


2 Answers

you might want to take a look here: https://stackabuse.com/how-to-loop-in-react-jsx/ . I hope this is what you are looking for

like image 185
Delano van londen Avatar answered Jul 18 '26 19:07

Delano van londen


The map() method is the most commonly used function to iterate over an array of data in JSX. You can attach the map() method to the array and pass a callback function that gets called for each iteration. When rendering the User component, pass a unique value to the key prop.

like image 30
Akshay phalphale Avatar answered Jul 18 '26 19:07

Akshay phalphale