0

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>
5
  • What exactly you are looking for ? i mean is there any error? whats the issue ? Commented Jan 29, 2020 at 11:34
  • 1
    this.state.characters is your entire var array ? Commented Jan 29, 2020 at 11:36
  • what is character? Commented Jan 29, 2020 at 11:36
  • 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 element Commented Jan 29, 2020 at 11:36
  • yes, this.state.characters is my entire var array Commented Jan 29, 2020 at 11:37

2 Answers 2

2

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>
        )
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.