others-How to do loop inside jsx in reactjs applications?

1. Purpose

In this post, I would demonstrate how to do loop inside JSX in reactjs applications.

2. The solution

2.1 The final result

Here is the final result of our test, I would loop with some list items inside a next.js application,which is a react.js application under the hood.

2.2 The first version

Before the final version, I have tried with some versions that have problems, such as follows:

import Link from "next/link";

export default function FirstPost() {
  const linkcount = 3;
  return (
    <>
      <h1>test loop post</h1>
      <h2>
      for(var i=0; i<{linkcount}; i++) {
        <Link href="/">
          <a>Back to home</a>
        </Link>
        }
      </h2>
    </>
  );
}

I have tried the above code ,and I got some errors when compiling the react application:

./pages/posts/test-loop.js
Error: error: Unexpected token `{`. Expected jsx identifier
  
   |
10 |       for(var i=0; i<{linkcount}; i++) {
   |                      ^

Caused by:
    0: failed to process js file
    1: Syntax Error

2.3 The final code

After learning this document , I found that if we want to make repeated components inside JSX, we should first build its children, then append the children to its parent. Just as follows:

import Link from "next/link";

function ItemList() {
  const nums = [1, 2, 3, 4, 5];
  const items = nums.map((num) => <li>{num}</li>); //build children
  return (
    <>
      <ul>{items}</ul>  //append children to its parent element
    </>
  );
}

export default function FirstPost() {
  return (
    <>
      <h1>test loop post</h1>
      <h2>
        <ItemList />  //use the final component
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
    </>
  );
}

The build and run , I got this:

And I still got this warning:



next-dev.js?3515:32 Warning: Each child in a list should have a unique "key" prop.

Check the render method of `ItemList`. See https://reactjs.org/link/warning-keys for more information.
    at li
    at ItemList
    at h2
    at FirstPost
    at App (webpack-internal:///./node_modules/next/dist/pages/_app.js:178:9)
    at StyleRegistry (webpack-internal:///./node_modules/styled-jsx/dist/stylesheet-registry.js:231:34)
    at ErrorBoundary (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ErrorBoundary.js:26:47)
    at ReactDevOverlay (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js:90:23)
    at Container (webpack-internal:///./node_modules/next/dist/client/index.js:331:9)
    at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:770:26)
    at Root (webpack-internal:///./node_modules/next/dist/client/index.js:891:27)

Because react.js need a key for each iterated items in the list. So I change the code as follows:

import Link from "next/link";

function ItemList() {
  const nums = [1, 2, 3, 4, 5];
  const items = nums.map((num) => <li key={num.toString()}>{num}</li>);
  return (
    <>
      <ul>{items}</ul>
    </>
  );
}

export default function FirstPost() {
  return (
    <>
      <h1>test loop post</h1>
      <h2>
        <ItemList />
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
    </>
  );
}


The most important code is:

 const items = nums.map((num) => <li key={num.toString()}>{num}</li>);

You can see that I added a property named key to the <li> component, and use the num.toString() as its value. Now the warning disappeared.

3. Summary

In this post, I demonstrated how to solve the problems when trying to do a loop inside JSX with react.js applications . The key point is to build the children component list at first, then append the list to its parent. That’s it, thanks for your reading.