目次
{question}
Quiz Complete
ホームページ ウェブフロントエンド jsチュートリアル React を使用したクイズ アプリケーションの構築

React を使用したクイズ アプリケーションの構築

Sep 10, 2024 am 11:31 AM

Building a Quiz Application with React

導入

このチュートリアルでは、React を使用して楽しくインタラクティブなクイズ Web サイトを構築する手順を説明します。このプロジェクトは、初心者が React でのユーザー入力の処理、状態の管理、動的コンテンツのレンダリングを練習するのに最適な方法です。

プロジェクト概要

クイズ Web サイトでは、ユーザーが多肢選択式の質問に回答し、選択した内容について即座にフィードバックを得ることができます。クイズの最後に、ユーザーには正解とともにスコアが表示されます。

特徴

  • インタラクティブなクイズ: ユーザーは質問に答えて、スコアを確認できます。
  • リアルタイム フィードバック: 選択した回答が正しいかどうかを即座に示します。
  • スコア計算: クイズ全体を通してスコアを追跡します。
  • 動的コンテンツ: 質問とオプションは、事前定義されたリストから動的に表示されます。

使用されている技術

  • React: ユーザー インターフェイスの構築とコンポーネントの状態の管理用。
  • CSS: アプリケーションのスタイルを設定します。
  • JavaScript: ロジックとクイズ機能の処理用。

プロジェクトの構造

プロジェクトは次のように構成されています:

├── public
├── src
│   ├── components
│   │   ├── Quiz.jsx
│   │   ├── Question.jsx
│   ├── App.jsx
│   ├── App.css
│   ├── index.js
│   └── index.css
├── package.json
└── README.md
ログイン後にコピー

主要コンポーネント

  • Quiz.jsx: クイズのロジックとスコア計算を処理します。
  • Question.jsx: 個々の質問を表示し、ユーザー入力を処理します。
  • App.jsx: レイアウトを管理し、クイズ コンポーネントをレンダリングします。

コードの説明

クイズコンポーネント

Quiz コンポーネントは、質問のレンダリング、スコアの計算、クイズの完了の処理を担当します。

import  { useEffect, useState } from "react";
import Result from "./Result";
import Question from "./Question";
const data = [
  {
    question: "What is the capital of France?",
    options: ["Paris", "Berlin", "Madrid", "Rome"],
    answer: "Paris",
  },
  {
    question: "What is the capital of Germany?",
    options: ["Berlin", "Munich", "Frankfurt", "Hamburg"],
    answer: "Berlin",
  },
  {
    question: "What is the capital of Spain?",
    options: ["Madrid", "Barcelona", "Seville", "Valencia"],
    answer: "Madrid",
  },
  {
    question: "What is the capital of Italy?",
    options: ["Rome", "Milan", "Naples", "Turin"],
    answer: "Rome",
  },
  {
    question: "What is the capital of the United Kingdom?",
    options: ["London", "Manchester", "Liverpool", "Birmingham"],
    answer: "London",
  },
  {
    question: "What is the capital of Canada?",
    options: ["Ottawa", "Toronto", "Vancouver", "Montreal"],
    answer: "Ottawa",
  },
  {
    question: "What is the capital of Australia?",
    options: ["Canberra", "Sydney", "Melbourne", "Brisbane"],
    answer: "Canberra",
  },
  {
    question: "What is the capital of Japan?",
    options: ["Tokyo", "Osaka", "Kyoto", "Nagoya"],
    answer: "Tokyo",
  },
  {
    question: "What is the capital of China?",
    options: ["Beijing", "Shanghai", "Guangzhou", "Shenzhen"],
    answer: "Beijing",
  },
  {
    question: "What is the capital of Russia?",
    options: ["Moscow", "Saint Petersburg", "Novosibirsk", "Yekaterinburg"],
    answer: "Moscow",
  },
  {
    question: "What is the capital of India?",
    options: ["New Delhi", "Mumbai", "Bangalore", "Chennai"],
    answer: "New Delhi",
  },
  {
    question: "What is the capital of Brazil?",
    options: ["Brasilia", "Rio de Janeiro", "Sao Paulo", "Salvador"],
    answer: "Brasilia",
  },
  {
    question: "What is the capital of Mexico?",
    options: ["Mexico City", "Guadalajara", "Monterrey", "Tijuana"],
    answer: "Mexico City",
  },
  {
    question: "What is the capital of South Africa?",
    options: ["Pretoria", "Johannesburg", "Cape Town", "Durban"],
    answer: "Pretoria",
  },
  {
    question: "What is the capital of Egypt?",
    options: ["Cairo", "Alexandria", "Giza", "Luxor"],
    answer: "Cairo",
  },
  {
    question: "What is the capital of Turkey?",
    options: ["Ankara", "Istanbul", "Izmir", "Antalya"],
    answer: "Ankara",
  },
  {
    question: "What is the capital of Argentina?",
    options: ["Buenos Aires", "Cordoba", "Rosario", "Mendoza"],
    answer: "Buenos Aires",
  },
  {
    question: "What is the capital of Nigeria?",
    options: ["Abuja", "Lagos", "Kano", "Ibadan"],
    answer: "Abuja",
  },
  {
    question: "What is the capital of Saudi Arabia?",
    options: ["Riyadh", "Jeddah", "Mecca", "Medina"],
    answer: "Riyadh",
  },
  {
    question: "What is the capital of Indonesia?",
    options: ["Jakarta", "Surabaya", "Bandung", "Medan"],
    answer: "Jakarta",
  },
  {
    question: "What is the capital of Thailand?",
    options: ["Bangkok", "Chiang Mai", "Phuket", "Pattaya"],
    answer: "Bangkok",
  },
  {
    question: "What is the capital of Malaysia?",
    options: ["Kuala Lumpur", "George Town", "Johor Bahru", "Malacca"],
    answer: "Kuala Lumpur",
  },
  {
    question: "What is the capital of the Philippines?",
    options: ["Manila", "Cebu City", "Davao City", "Quezon City"],
    answer: "Manila",
  },
  {
    question: "What is the capital of Vietnam?",
    options: ["Hanoi", "Ho Chi Minh City", "Da Nang", "Hai Phong"],
    answer: "Hanoi",
  },
  {
    question: "What is the capital of South Korea?",
    options: ["Seoul", "Busan", "Incheon", "Daegu"],
    answer: "Seoul",
  },
];
const Quiz = () => {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [score, setScore] = useState(0);
  const [showResult, setShowResult] = useState(false);
  const [timer, setTimer] = useState(30);
  const [showNextButton, setShowNextButton] = useState(true);

  useEffect(() => {
    if (timer === 0) {
      handleNext();
    }
    const timerId = setTimeout(() => setTimer(timer - 1), 1000);
    return () => clearTimeout(timerId);
  }, [timer]);

  const handleAnswer = (selectedOption) => {
    if (selectedOption === data[currentQuestion].answer) {
      setScore(score + 1);
    }
    setShowNextButton(true); // Show the next button after answering
  };

  const handleNext = () => {
    const nextQuestion = currentQuestion + 1;
    if (nextQuestion ;
  }

  return (
    <div classname="quiz">
<div classname="countandTime">
<div classname="questionNumber">
       Question :  {currentQuestion + 1} <b>/</b> {data.length}
      </div>
      <div classname="timer">Time left : {timer} seconds</div>
</div>
      <question question="{data[currentQuestion].question}" options="{data[currentQuestion].options}" onanswer="{handleAnswer}" onnext="{handleNext}" shownextbutton="{showNextButton}"></question>
    </div>
  );
};

export default Quiz;

ログイン後にコピー

クイズ コンポーネントは、現在の質問のインデックスとスコアを管理します。また、クイズがいつ終了したかを追跡し、すべての質問に回答すると最終スコアが表示されます。

質問コンポーネント

Question コンポーネントは各質問の表示を処理し、ユーザーが回答を選択できるようにします。

const Question = ({ question, options, onAnswer, onNext, showNextButton }) => {
  return (
    <div classname="question">
      <h2 id="question">{question}</h2>
      {options.map((option, index) => (
        <button classname="option" key="{index}" onclick="{()"> onAnswer(option)}>
          {option}
        </button>
      ))}
      {showNextButton && <button classname="next" onclick="{onNext}">Next </button>}
    </div>
  );
};

export default Question;

ログイン後にコピー

このコンポーネントは、質問とそのオプションを含むデータ プロパティを取得し、動的にレンダリングします。 handleAnswer 関数は、選択されたオプションを処理します。

アプリコンポーネント

App コンポーネントはレイアウトを管理し、Quiz コンポーネントをレンダリングします。

import Quiz from "./components/Quiz";
import "./App.css";
import React を使用したクイズ アプリケーションの構築 from "./assets/images/quizReact を使用したクイズ アプリケーションの構築.png";
const App = () => {
  return (
    <div classname="app">
      <img classname="React を使用したクイズ アプリケーションの構築" src="%7BReact" alt="React を使用したクイズ アプリケーションの構築">
      <quiz></quiz>
      <p classname="footer">Made with ❤️ by Abhishek Gurjar</p>
    </div>
  );
};

export default App;

ログイン後にコピー

このコンポーネントはヘッダーとフッターでページを構成し、クイズ コンポーネントは中央に表示されます。

結果コンポーネント

結果コンポーネントは、ユーザーが回答を送信した後にクイズのスコアを表示する役割を果たします。ユーザーの回答と正解を比較してスコアを計算し、正解した質問の数に関するフィードバックを提供します。

const Result = ({ score, totalQuestion }) => {
  return (
    <div classname="result">
      <h2 id="Quiz-Complete">Quiz Complete</h2>
      <p>Your score is {score} out of {totalQuestion}</p>
    </div>
  );
}

export default Result;

ログイン後にコピー

このコンポーネントでは、スコアと質問の合計数が小道具として渡されます。スコアに基づいて、コンポーネントはユーザーにメッセージを表示し、全問正解したことを賞賛するか、練習を続けるよう奨励します。この動的なフィードバックは、ユーザーが自分のパフォーマンスを理解するのに役立ちます。

CSS スタイル

CSS により、クイズのすっきりとしたシンプルなレイアウトが保証されます。クイズ コンポーネントのスタイルを設定し、使いやすいビジュアルを提供します。

* {
  box-sizing: border-box;
}
body {
  background-color: #cce2c2;
  color: black;
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}
.app {
  width: 100%;

  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;
}
.app img {
  margin: 50px;
}

/* Quiz */
.quiz {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 60%;
  margin: 0 auto;
}
.countandTime {
  display: flex;
  align-items: center;
  gap: 300px;
}
.questionNumber {
  font-size: 20px;
  background-color: #fec33d;
  padding: 10px;
  border-radius: 10px;
  font-weight: bold;
}
.timer {
  font-size: 18px;
  background-color: #44b845;
  color: white;
  padding: 10px;
  border-radius: 10px;
  font-weight: bold;
}

/* Question */

.question {
  margin-top: 20px;
}
.question h2 {
  background-color: #eaf0e7;
  width: 690px;
  padding: 30px;
  border-radius: 10px;
}
.question .option {
  display: flex;
  margin-block: 20px;
  flex-direction: column;
  align-items: flex-start;
  background-color: #eaf0e7;
  padding: 20px;
  border-radius: 10px;
  font-size: 18px;
  width: 690px;
}

.question .next {
  font-size: 25px;
  color: white;
  background-color: #35bd3a;
  border: none;
  padding: 10px;
  width: 100px;
  border-radius: 10px;

  margin-left: 590px;
}

/* Result */

.result {
  border-radius: 19px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  width: 500px;
  height: 300px;
  margin-top: 140px;
  background-color: #35bd3a;
  color: white;
}
.result h2{
  font-size: 40px;
}
.result p{
  font-size: 25px;
}

.footer {
  margin: 40px;
}
ログイン後にコピー

スタイル設定により、レイアウトが中央に配置され、クイズのオプションにホバー効果が提供され、よりインタラクティブになります。

インストールと使用方法

このプロジェクトを開始するには、リポジトリのクローンを作成し、依存関係をインストールします。

git clone https://github.com/abhishekgurjar-in/quiz-website.git
cd quiz-website
npm install
npm start
ログイン後にコピー

これにより開発サーバーが起動し、アプリケーションが http://localhost:3000 で実行されます。

ライブデモ

ここでクイズ Web サイトのライブデモをチェックしてください。

結論

このクイズ Web サイトは、React スキルを向上させたい初心者にとって優れたプロジェクトです。これは、状態の管理、動的コンテンツのレンダリング、ユーザー入力の処理を実践するための魅力的な方法を提供します。

クレジット

  • インスピレーション: このプロジェクトは、楽しみと学習を組み合わせた古典的なクイズ ゲームからインスピレーションを得ています。

著者

Abhishek Gurjar は、インタラクティブで魅力的な Web アプリケーションの構築に情熱を注ぐ Web 開発者です。彼の作品は GitHub でフォローできます。

以上がReact を使用したクイズ アプリケーションの構築の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JavaScriptの文字列文字を交換します JavaScriptの文字列文字を交換します Mar 11, 2025 am 12:07 AM

JavaScriptの文字列文字を交換します

jQuery日付が有効かどうかを確認します jQuery日付が有効かどうかを確認します Mar 01, 2025 am 08:51 AM

jQuery日付が有効かどうかを確認します

jQueryは要素のパディング/マージンを取得します jQueryは要素のパディング/マージンを取得します Mar 01, 2025 am 08:53 AM

jQueryは要素のパディング/マージンを取得します

10 jQuery Accordionsタブ 10 jQuery Accordionsタブ Mar 01, 2025 am 01:34 AM

10 jQuery Accordionsタブ

10 jqueryプラグインをチェックする価値があります 10 jqueryプラグインをチェックする価値があります Mar 01, 2025 am 01:29 AM

10 jqueryプラグインをチェックする価値があります

ノードとHTTPコンソールを使用したHTTPデバッグ ノードとHTTPコンソールを使用したHTTPデバッグ Mar 01, 2025 am 01:37 AM

ノードとHTTPコンソールを使用したHTTPデバッグ

カスタムGoogle検索APIセットアップチュートリアル カスタムGoogle検索APIセットアップチュートリアル Mar 04, 2025 am 01:06 AM

カスタムGoogle検索APIセットアップチュートリアル

jQueryはscrollbarをdivに追加します jQueryはscrollbarをdivに追加します Mar 01, 2025 am 01:30 AM

jQueryはscrollbarをdivに追加します

See all articles