Search code examples
arraysreactjsnestedrenderchunks

How do I render a nested Array with React.js?


I am new to react.js and I have stumbled upon a subject I can't wrap my head around. I have a long array of items which I want to display in two different rows, which is why I take chunks out of this array and add them to a nested array without key and values like so:

constructor(props) {
        super(props)
        this.state = {
            characters: [["Anakin","Darth Vader","Snoke"], ["Darth Maul", "Yoda", "Luke Skywalker"]],
        }
    }

In the render function of the "Characters" component I use the map function and what I want is each array to be passed to the component "Subarray":

Characters component

 render() {
        return (
            <div>
                {this.state.characters.map((item, index )=> <Subarray key={index} title={item}></Subarray>)}
            </div>
        )
    }

And then in the "Subarray" component I want to add a html element to every element in that array:

Subarray component

export class Subarray extends Component {
    render() {
        return (
            <div>
               {this.props.title}
            </div>
        )
    }
}

I can't get each element of the array to be wrapped within a div element:

Output:

<div><div>AnakinDarth VaderSnoke</div><div>Darth MaulYodaLuke Skywalker</div></div>

Solution

  • You can do this, assuming this.props.title contains ["Anakin","Darth Vader","Snoke"] :

    export class Subarray extends Component {
        render() {
            return (
               <div>
                {this.props.title.map((each, index) => <div key={index}>{each}</div>)}
               </div>
            )
        }
    }