最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to loop React Elements for a specific amount of times? - Stack Overflow

programmeradmin2浏览0评论

I am trying to make a looper ponent so that I can loop any of its children for a specific amount of time. How can I do that?

// Looper

function Looper({ children, array }) {
    return (
      <div>
        {array.map((item) => (
          <div key={item}>{children}</div>
        ))}
      </div>
    );
  }
  

// It works, but it needs a dummy array that I don't want.

<Looper array={[1, 2, 3, 4, 5]}>
    <span>Hello Guys..</span>
</Looper>

I am trying to make a looper ponent so that I can loop any of its children for a specific amount of time. How can I do that?

// Looper

function Looper({ children, array }) {
    return (
      <div>
        {array.map((item) => (
          <div key={item}>{children}</div>
        ))}
      </div>
    );
  }
  

// It works, but it needs a dummy array that I don't want.

<Looper array={[1, 2, 3, 4, 5]}>
    <span>Hello Guys..</span>
</Looper>
Share Improve this question asked Dec 3, 2021 at 11:33 Code LoverCode Lover 531 silver badge5 bronze badges 1
  • 1 Why not [...Array(5)].map((_,idx) => (<div key={idx} ..? – Yevhen Horbunkov Commented Dec 3, 2021 at 11:41
Add a ment  | 

2 Answers 2

Reset to default 6

You can create an array of incrementing numbers on the fly using [...Array(times).keys()], like so:

// Looper

function Looper({ children, times }) {
    const keys = [...Array(times).keys()];
    return (
      <div>
        {keys.map((item) => (
          <div key={item}>{children}</div>
        ))}
      </div>
    );
  }
  
<Looper times={5}>
    <span>Hello Guys..</span>
</Looper>

replace your map function with a for loop and pass a count i:e number of times you want the looper to render, and use that index as a key for the child divs then push them into an array. Finally, return that array of child divs. Check out this link if you want to go with this approach Loop inside React JSX

发布评论

评论列表(0)

  1. 暂无评论