Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach() in React JSX does not output any HTML

People also ask

Why forEach does not work in React?

forEach() is not designed to return a value. Its primary purpose is to transform every array element, but nothing else. The method doesn't return a new array; it returns undefined . Instead, React developers use an alternative method, .

Can we use forEach in JSX?

forEach method can be used when you need to call a function for every element in an array. However, forEach() can't be used to iterate over an array directly in your JSX code.

Does JSX allows us to write HTML in React?

JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.


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;