amg
amg

Reputation: 1

TypeError: Cannot read property 'map' of undefined1

I am working on a Quiz application on React I have a problem with the map function, I use this function to create the response buttons for the problem with the map function levels. I have an error message "TypeError: Cannot read property 'map' of undefined"

import React, {useState, component} from "react";

const QuestionBox = ({question, options, selected}) => {
  const [answer, setAnswer] = useState(options);
  return (
    <div className="questionBox">
      <p className="question">{question}</p>
      {answer.map((text, index) => (
        <button
          key={index}
          className="answerBtn"
          onClick={() => {
            setAnswer([text]);
            selected(text);
          }}
        >
          {text}
        </button>
      ))}

    </div>
  );
};

export default QuestionBox;

Upvotes: 0

Views: 50

Answers (2)

Khabir
Khabir

Reputation: 5854

As you using setAnswer to set an object Answer with is also set from option. So I replace the Answer.map with options.map and remove array symbol from setAnswer. Please try this code.

import React, {useState, component} from "react";

const QuestionBox = ({question, options, selected}) => {
  const [answer, setAnswer] = useState({});
  return (
    <div className="questionBox">
      <p className="question">{question}</p>
      {options.map((text, index) => (
        <button
          key={index}
          className="answerBtn"
          onClick={() => {
            setAnswer(text);
            selected(text);
          }}
        >
          {text}
        </button>
      ))}

    </div>
  );
};

export default QuestionBox;

Upvotes: 1

bilwit
bilwit

Reputation: 819

The options prop is undefined at the time of mount and you're initializing answer with it. You can simply add a check condition before the map:

return (
  <div className="questionBox">
    <p className="question">{question}</p>
    {answer ? answer.map((text, index) => (
    <button
      key={index}
      className="answerBtn"
      onClick={() => {
        setAnswer([text]);
        selected(text);
      }}
    >
      {text}
    </button>
  )) : null}

  </div>
);

Or otherwise initialize it with a default "options" array if the prop doesn't exist.

const QuestionBox = ({question, options = ['Default Value'], selected}) => {...

or

const [answer, setAnswer] = useState(options ? options : ['Default Value']);

Upvotes: 0

Related Questions