Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.4 kB
4
Indexable
Never
import React from 'react';
import { useState } from 'react';
import { data } from './data.js';

function App() {
  const [questions, setQuestions] = useState(data);
  const [index, setIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState('');
  const [studentAnswers, setStudentAnswers] = useState([]);

  const handleAnswerChange = (event) => {
    setSelectedAnswer(event.target.value);
  };

  const handleScore = () => {
    let score = 0;
    for (let i = 0; i < questions.length; i++) {
      if (questions[i].answers[questions[i].correctIndex] === studentAnswers[i]) {
        score++;
      }
    }
    alert('You got ' + score + ' out of ' + questions.length + ' correct!');
  };

  const handleClick = () => {
    console.log(selectedAnswer);
    setStudentAnswers([...studentAnswers, selectedAnswer]);
    setIndex(index + 1);
  };

  let question = questions[index];

  return (
    <div className='w-[60%] h-[1000px] mx-auto mt-[100px] border-4'>
      <div>
        <h1 className='w-[45%] text-6xl font-bold border-2 bg-slate-100 p-4 m-4 mx-10' > Question number {index + 1} of {questions.length}</h1>
        <h1 className='text-5xl  h-[100px] bg-slate-100 shadow-lg  text-center mt-10 mx-8 items-center pt-5 '>{question.question}</h1>
        </div>
        <div>
          {question.answers.map((answer, i) => (
            <div key={i}>
              <div className='mt-[80px] mx-10'>
                <input className='w-[30px] h-[30px]'
                  type='radio'
                  name='answer'
                  value={answer}
                  onChange={handleAnswerChange}
                />
                <label className='text-6xl p-2'>{answer}</label>
              </div>
            </div>
          ))}
        </div>
        {index < questions.length - 1 && (
          <button onClick={handleClick} className="w-[200px] h-[80px] bg-indigo-500 rounded-lg text-4xl font-bold text-white ml-[87%] mt-4">
            Next
          </button>
        )}
        {index === questions.length - 1 && (
          <button onClick={handleScore} className="w-[200px] h-[80px] bg-indigo-500 rounded-lg text-4xl font-bold text-white ml-[87%] mt-4">
            Submit
          </button>
        )}
        
      
    </div>
  );
}
export default App;