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, .
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With