Deke
Deke

Reputation: 4639

adding map function within map function is not displaying any items

I have two sets of data which are array of items from the json file. Mapping through props.detailData.map alone displays the content. But when I add props.imageLinks.map and make it map within map in order to add `a href', nothing gets displayed on the screen. Infact no error is thrown in the console. What is wrong?

import React from "react";


const Descriptions = (props) => {
   console.log(props.detailData)
   {/************["a", "b", "c", "d"]**********/}

   console.log(props.imageLinks)
   {/************["http://www.l.com", "http://www.m.com", "http://www.n.com", "http://www.o.com"]**********/}

   return (
       <div> 
          <div> 
             {props.imageLinks.map((l, i) =>
                {props.detailData.map((d, i) =>
                  <li key={i}>
                    {d} 
                    <div>
                      <a href={l}> view images </a>
                    </div>
                  </li>
                )}
             )}
         </div>
      </div>
    )
}

export default Descriptions;

Upvotes: 0

Views: 65

Answers (2)

Viet
Viet

Reputation: 6943

If you goal is to have 16 <li> then use the code from @JJJ above because each iteration will go through each and every item in each array (4x4).

If your goal is to have 4 <li> with detailData and imageLinks then your best bet would be merging the 2 arrays like so:

const detailData = ["a", "b", "c", "d"];
const imageLinks = ["http://www.l.com", "http://www.m.com", "http://www.n.com", "http://www.o.com"];
let res = detailData.map((key, i) => {
    return [key, imageLinks[i]]
});
console.log(res);
return (
<div className="App">
{res.map((l, i) => (
    <li key={i}>
        {l[0]} 
        <div>
        <a href={l[1]}> view images </a>
        </div>
    </li>
))}
</div>

Obviously there are ways to merge the 2 arrays. This is just one of them.

Upvotes: 1

JJJ
JJJ

Reputation: 33163

The curly brackets inside the inner map function signify a function block, not the JSX template syntax. The function doesn't return anything which is why it also doesn't display anything. Remove the brackets.

{props.imageLinks.map((l, i) =>
    props.detailData.map((d, i) =>
      <li key={i}>
        {d} 
        <div>
          <a href={l}> view images </a>
        </div>
      </li>
    )
)} 

Upvotes: 1

Related Questions