204

I have a object that I want to output via React:

question = {
    text: "Is this a good question?",
    answers: [
       "Yes",
       "No",
       "I don't know"
    ]
} 

and my react component (cut down), is another component

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.forEach(answer => {     
           console.log("Entered");  //This does ifre                       
           <Answer answer={answer} />   //THIS DOES NOT WORK 
        })}
}

export default QuestionSet;

as you can see from the snippit above, i'm trying to insert an array of the component Answer by using the array Answers in props, it does itterate but is not outputted into HTML.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Michael
  • 8,229
  • 20
  • 61
  • 113

1 Answers1

396

You need to pass an array of element to jsx. The problem is that forEach does not return anything (i.e it returns undefined). So it's better to use map because map returns an array:

class QuestionSet extends Component {
render(){ 
    <div className="container">
       <h1>{this.props.question.text}</h1>
       {this.props.question.answers.map((answer, i) => {     
           console.log("Entered");                 
           // Return the element. Also pass key     
           return (<Answer key={answer} answer={answer} />) 
        })}
}

export default QuestionSet;
mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37
  • 13
    Use var i as key is not a good choice in some situation for virtual dom. – maquannene Mar 01 '19 at 09:02
  • 6
    @maquannene Indeed thanks for pointing that out. Here's a good post on why https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318 – cyberwombat Mar 11 '20 at 18:24
  • 4
    FWIW you can also pass in other kinds of collections. You just need to unroll them so they'll work with `.map()`. e.g. `Object.keys(collection).map(key => ...` and assign a variable for conveniently working with `collection[key]` – John Kaster Apr 03 '20 at 18:48