0
votes

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>
2
What exactly you are looking for ? i mean is there any error? whats the issue ?coderLogs
this.state.characters is your entire var array ?TBouder
what is character?Rajaprabhu Aravindasamy
The output is displayed like this: <div><div>AnakinDarth VaderSnoke</div><div>Darth MaulYodaLuke Skywalker</div></div>. They don't get wrapped within a html elementChristopher
yes, this.state.characters is my entire var arrayChristopher

2 Answers

2
votes

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>
        )
    }
}
1
votes

I think that you have to change Subarray to be something like

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

in this way you loop through each item in the subarray and render every one of them