user5381829
user5381829

Reputation:

ReactJS - Map inside a map

I am working on a ReactJS & Redux app. At some point, I have a list of elements (notes), each one of them having an array (subtasks). I would like to display all the elements, and for each of them, display the content of their array.

I tried this :

 render(){
    return(
        <div>
            <h3>{this.props.match.params.user}'s board</h3>

            <Link to={`/settings/${this.props.match.params.user}`}>
                <button>Settings</button>
            </Link>

            <Link to={`/new/${this.props.match.params.user}`}>
                <button>Add note</button>
            </Link>

            {
                this.props.notes.map((item,index) => 
                    <Link to={`/details/${item.name}`}>
                        <h4 key={index}>{item.name}</h4>

                        item.subtasks.map((sub, subindex)=>
                            <p key={subindex}>{sub}</p>)

                    </Link>
                )
            }
        </div>
    );
}

But I got:

Uncaught ReferenceError: subindex is not defined

What's the right way to do it?

Upvotes: 7

Views: 43829

Answers (3)

bhautik
bhautik

Reputation: 7

I have used in one of my project like this in react js where i have to show only slotsData .

const { data }=useGroundCourtsList(useParam.groundCourdId);
const slotsData= data?.getGroundCourts?.docs.map((court) => ({
      slots: court.courtSlots.map((slot) => ({
        day: slot.day.slice(0, 3),
        slots: slot.slots,
   })),
}))

Upvotes: 0

GMKHussain
GMKHussain

Reputation: 4719

An example with Vanilla JavaScript you can implement same way in react as you wish.

let users = [
        { 
          name: "Amoos",
          skills: ["PHP", "MySQL"]
        },
        {
          name: "Rifat",
          skills: ["JavaScript", "React", "HTML"]
        }
    ];
    

  users.map(( user, index ) => { 
          console.log(`User: ${user.name}`)
          {
            user.skills.map(( skill, subIndex) => {
              console.log(`Skill # ${subIndex}: ${skill} `)     
            })
          }
      }
    )

Upvotes: 5

Prakash Sharma
Prakash Sharma

Reputation: 16482

You need to wrap second map, inside {} brackets like this

{
    this.props.notes.map((item,index) => 
        <Link to={`/details/${item.name}`}>
            <h4 key={index}>{item.name}</h4>

            { 
                item.subtasks.map((sub, subindex) =>
                    <p key={subindex}>{sub}</p>)
            }

        </Link>
    )
}

Upvotes: 25

Related Questions