How do i render an array of object in react

Hi, I am new to react, and I would like to know how I can render an array of object(questions & answers).

Here is what I have done so far:

class App extends React. Component {

  constructor(props){
super(props);
this.state=({
question : [],
})
}
questions = [
    {
      question: "Who is the strongest?",
      answers: {
        a: "Superman",
        b: "The Terminator",
        c: "Waluigi, obviously"
      },
     
  ];
  handleQuestion(){

this.setState({
question: questions
})
}
render(){

return(

<div className = "container">
   <button type="button" onClick={()=>this.handleQuestion()}>
          Show Question
        </button>
  
  </div>

My plan is to have the user click the "Show Question " button to mutate state by calling the handleQuestion(), but i got the error: questions is not defined.

I want to know what am doing wrong, or is there a more realistic way of doing it

Anything defined within the class App must be accessed within App using this.<thing>. There’s no questions, only this.questions.

Assuming you want to render all questions at once, you’ll first need to map over that array, then render the question itself, then get Object.keys of the answers object and use that to map over the properties of that object.

Here’s a simplified (non-react/JSX) version:

const questions = [
  {
    question: "Who is the strongest?",
    answers: {
      a: "Superman",
      b: "The Terminator",
      c: "Waluigi, obviously"
    }
  },
  {
    question: "How many roads must a man walk down?",
    answers: {
      a: "42",
      b: "The answer is blowing in the wind"
    }
  }
];

questions.map(q => {

  const answers = Object.keys(q.answers).map(key => {
    return `Answer ${key}: ${q.answers[key]}`;
  }).join('\n')

  return `QUESTION: ${q.question}\n\n${answers}`;
}).join('\n\n---\n\n');

Note that in React, you won’t need to join anything — an array of JSX elements will automatically be rendered consecutively.


I’ve also edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums