Home > Back-end >  Looping <li> elements in JSX React
Looping <li> elements in JSX React

Time:09-26

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.

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

JSX treat an array like a multiple elements. You can code like this:

function NumberList() {
  return (
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  );
}

Or use an array. But when use an array, we need to add an unique key attribute for each element in array:

function NumberList() {
  const listItems = [
    <li key="1">1</li>,
    <li key="2">2</li>,
    <li key="3">3</li>,
  ];

  return (
    <ul>{listItems}</ul>
  );
}

If you want to using one element, you can wrap all elements to a Fragment:

function NumberList() {
  const listItems = (
    <>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </>
  );

  return (
    <ul>{listItems}</ul>
  );
}

Use map is same as using array:

function NumberList() {
  const numbers = [1, 2, 3];
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>
      {number}
    </li>
  );

  return (
    <ul>{listItems}</ul>
  );
}

or using map directly in JSX:

function NumberList() {
  const numbers = [1, 2, 3];

  return (
    <ul>
      {
        numbers.map((number) =>
          <li key={number.toString()}>
            {number}
          </li>
      )}
    </ul>
  );
}

About key attribute, please refer to React's document: (https://reactjs.org/docs/lists-and-keys.html#keys)[https://reactjs.org/docs/lists-and-keys.html#keys].

  • Related