skip to Main Content
const emptyRow = 3;

How can I map on this if it’s a number and not an array?
something like:

    emptyRow.map(el => {
return (
<div>place items here</div>
)
})

The purpose to this is that I would like to create divs dynamically based on the number of emptyRows.

4

Answers


  1. For this you can just use for loop

    const emptyRow = 3;
    for (let i = 1; i <=emptyRow; i++) {
        return (
          <div>place items here</div>
        )
     }
    

    Hope this helps…

    Login or Signup to reply.
  2. Doesn’t really work that way… you seem like maybe you’re confusing map with repeat, which I believe only works on strings.

    What you can do is create a range. Javascript doesn’t have a native range function, but you can write it pretty easily:

        const range = (length, offset = 0) => Array.from({length}, (_, n) => n + offset);
    
        // logs: [ "<div/>", "<div/>", "<div/>" ]
        console.log(range(3).map(() => `<div/>`));
    
        // logs [ "<div key='0' />", "<div key='1' />", "<div key='2' />" ]
        console.log(range(3).map((i) => `<div key='${i}'/>`));
    
        // logs: [ "<div key='2'/>", "<div key='3'/>", "<div key='4'/>" ]
        console.log(range(3, 2).map((i) => `<div key='${i}'/>`));
    Login or Signup to reply.
  3. Not pretty, but it’s simple and it works.

    const emptyRows = 3;
    Array(emptyRows).fill(0).map(el => {
      return (
        <div>place items here</div>
      )
    })
    
    Login or Signup to reply.
  4. A slightly more elegant and concise way to achieve this is by using Array.from() directly, which avoids the need to use fill():

    const emptyRows = 3;
    
    Array.from({ length: emptyRows }, (_, index) => (
      <div key={index}>place items here</div>
    ));
    

    Why Array.from()?

    • No need for fill(0): Array.from() allows you to directly specify the length of the array and map over it at the same time.

    • Concise: It reduces the amount of code and increases readability by combining array creation and mapping into a single function.

    This will create the desired number of <div> elements dynamically, and you can adjust the number in emptyRows as needed. Plus, it’s easy to understand at a glance!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search