ReactJS - Map inside a map
Asked Answered
V

3

7

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?

Vagrant answered 4/3, 2018 at 9:58 Comment(1)
JavaScript embedded inside JSX must always be wrapped in {}Privative
J
25

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>
    )
}
Juliajulian answered 4/3, 2018 at 10:2 Comment(0)
I
5

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} `)     
            })
          }
      }
    )
Inelastic answered 4/8, 2022 at 11:30 Comment(0)
R
0

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,
   })),
}))
Rettarettig answered 19/3 at 7:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.