skip to Main Content

I have mapping function like this:

function MyFunction({rows}) {
        return(
        rows
        .map((info, index) => (
            <td key = {someNum}>
                <p>some info</p>
            </td>
        )));
}

and I want to add something that will create new rows after the index hits five:

function MyFunction({rows}) {
        return(
        rows
        .map((info, index) => (
            {(index+1 %5 === 0 || index === 0) && <tr>}
            <td key = {someNum}>
                <p>some info</p>
            </td>
            {(index+1 %5 === 0) && </tr>}
        )));
}

I can’t get it to work, any ideas?

I’ve tried a lot of different syntax inside those curly brackets, but cant seem to figure out how to do it.

2

Answers


  1. I think you are missing a return statement

    if you use arrow function like

    const myFunction = () => doSomething(); // you don't need return
    

    but if you use it like that

    const myFunction = () => {
      return doSomething(); // you need return
    }
    

    In your case

       return(
            rows
            .map((info, index) => (
    // here missing a return 
                {(index+1 %5 === 0 || index === 0) && <tr>}
                <td key = {someNum}> // 
                    <p>some info</p>
                </td>
                {(index+1 %5 === 0) && </tr>}
            )));
    
    Login or Signup to reply.
  2. const chunk = (arr, size) => 
        Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
           arr.slice(i * size, i * size + size)
    );
    
    const results = chunk(rows, 5);
    
    return(
        results.map((array) => (
          <>
            <tr>
            {array.map((info) => (
               <td key = {someNum}>
                  <p>some info</p>
               </td>
            ))}
            </tr>
          </>
       ))
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search