Tushar Gaurabh jha
Tushar Gaurabh jha

Reputation: 593

looping in Typescript

I am making a quiz page where after quiz is finished I am displaying all the correct answers. For displaying answers I am taking a list and adding all the question and correct and in a list and rendering the list but I am getting the repeated answers I don't know what is the Issue is, Please Help.

Screenshot => https://ibb.co/RPz862t

import React from "react";

type Props = {
    questions: string | any[];
};

const items: any[] = [];
const iterateQ = (question:string | any[]) => {
  let a = 0;
  let size = question.length;
  while(a < size) {
    items.push(
      <div>
        <div className="font-normal">
            Question No: {a}
        </div>
        <div className="font-bold">
            {question[a].question}
        </div>
        <div className="bg-green-300 font-bold font-color p-1 rounded-lg shadow-lg w-full mt-2">
            {question[a].answer[question[a].correctAnswer].answerText}
        </div>
      </div>
    );
    a = a + 1;
  }
  return items;
}


const ShowAns: React.FC<Props> = ({
    questions,
}) => (
    <>
       <div className="justify-center items-center">
         {iterateQ(questions)}
       </div>
    </>
);

export default ShowAns;


Upvotes: 0

Views: 99

Answers (1)

djolf
djolf

Reputation: 1196

Try this code

EDIT(2023) Updated code to be using the React way correctly.

import React from "react";

type Props = {
    questions: string | any[];
};

const iterateQ = (questions:string | any[]) => (
  <>
    {questions.map((q: any, i: number) => {
      <div>
        <div className="font-normal">
          Question No: {i}
        </div>
        <div className="font-bold">
          {q.question}
        </div>
        <div className="bg-green-300 font-bold font-color p-1 rounded-lg 
          shadow-lg w-full mt-2">
          {q.answer[q.correctAnswer].answerText}
        </div>
      </div>
    })}
  </>
);


const ShowAns: React.FC<Props> = ({questions}) => (
    <>
       <div className="justify-center items-center">
         {iterateQ(questions)}
       </div>
    </>
);

export default ShowAns;

Upvotes: 1

Related Questions