Search code examples
javascriptreactjsecmascript-6

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?


Solution

  • 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>
        )
    }