forEach() in React JSX does not output any HTML

ReactjsReact Props

Reactjs Problem Overview


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.

Reactjs Solutions


Solution 1 - Reactjs

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - ReactjsPrakash SharmaView Answer on Stackoverflow