Build a React.js Trivia Quiz Game With High Score in Browser Using HTML5 CSS3 and Javascript Full Project For Beginners

 

 

 

index.html

 

 

<head>
  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
</head>
<body>

<div id="root"> </div>
  
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

 

 

style.css

 

 

body{
  --main-color: #DC00FF;
  --color-1: #FFC219;
  --color-2: #14CC96;
  background: var(--main-color) ;
  padding: 0;
  margin: 0;
  height: 100vh;
  color: var(--main-color);
  font-family: 'Lato', sans-serif;
}


#outer{
  margin-top: 2rem;
  padding: 5vh 5vw;
  text-align: center;
  
}

#main{
  padding: 4vh 4vw;
  text-align: center;
  border: 0.4rem solid rgba(0,0,0,0.25);
  border-radius: 1rem;
  display: inline-block;
  width: 16rem;
  background-color: var(--color-1);
  box-shadow: 0rem 0rem 10rem 2rem var(--color-1);
}

#question{
  font-size: 1.3rem;
  padding: 0.5rem;
  text-shadow: 1px 1px rgba(0,0,0,0.2);
}

#question-group{
  padding: 0.5rem;  
  
}

button{
  display: block;
  padding: 0.5rem 1rem;
  margin: 0.3rem 0;
  width: 16rem;
  border-radius: 0.3rem;
  background-color: var(--main-color);
  color: var(--color-1);
  border: 3px solid rgba(0,0,0,0.2);
  box-shadow: 0.1rem 0.1rem 0.1rem rgba(0,0,0,0.3);
  background-color: var(--color-2);
  color: white;
  outline: none;
  font-size: 1rem;
  text-shadow: 1px 1px 5px  rgba(0,0,0,0.5);
}
button:active{
  box-shadow:none;
  transform: translateY(3px);
  outline: none;
  background-color: var(--main-color);
  color: var(--color-1);
  font-weight:bold;
  transition: 0.1s;
}


button:hover{
  cursor: pointer;
}

#question-number{
  padding: 0.5rem;
  text-align: left;
}

#score-group{
  padding: 0.5rem;
}

.scores{
  display: inline-block;
  float: left;
}

.right{
  float: right;
}

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}

@media only screen and (max-width: 500px) {
  #main{
    box-shadow: 0rem 0rem 5rem 1rem var(--color-1);
  }
}

 

 

script.js

 

 

const MAX_QUESTIONS = 10;
var originalQuestions =[
  {
    question: "Who was the first man on the Moon?",
    answers: ["Yuri Gagarin", "Neil Armstrong", "Elon Musk", "Buzz Astral"],
    correctIndex: 1
  },
  {
    question: "Who won the FIFA World Cup in 2018?",
    answers: ["Croatia", "Brazil", "France", "Italy"],
    correctIndex: 2
  },
  {
    question: "What is the capital of Germany?",
    answers: ["Vienna", "Frankfurt", "Munich", "Berlin"],
    correctIndex: 3
  },
  {
    question: "When did United States got independence?",
    answers: ["1773", "1607", "1776", "1803"],
    correctIndex: 2
  },
  {
    question: "What's the tallest building in the United States?",
    answers: ["One World Trade Center", "Sears Tower", "Empire State Building", "Space Needle"],
    correctIndex: 0
  },
  {
    question: "Which year Curiosity robotic space probe landed on Mars?",
    answers: ["1997", "2001", "2012", "2016"],
    correctIndex: 2
  },
  {
    question: "How many electrons does oxygen have?",
    answers: ["2", "4", "6", "8"],
    correctIndex: 3
  },
  {
    question: "What is the longest river in the world?",
    answers: ["Amazon River", "The Nile", "Yellow River", "Mississippi River"],
    correctIndex: 1
  },
  {
    question: "What is the largest continent in the world?",
    answers: ["Asia", "Africa", "North America", "South America"],
    correctIndex: 0
  },
  {
    question: "Who was the 3rd president of the United States?",
    answers: ["George Washington", "Thomas Jefferson", "Abraham Lincoln", "Benjamin Franklin"],
    correctIndex: 1
  },
  {
    question: "What temperature does water boil at?",
    answers: ["100 C", "100 F", "212 C", "37.7 C"],
    correctIndex: 0
  },
  {
    question: "What does the roman numeral C represent?",
    answers: ["100", "500", "1000", "5000"],
    correctIndex: 0
  },
  {
    question: "What nationality was Chopin? ",
    answers: ["German", "French", "Italian", "Polish"],
    correctIndex: 3
  },
  {
    question: "Who painted Mona Lisa? ",
    answers: ["Michelangelo", "Claude Monet", "Da Vinci", "Raphael"],
    correctIndex: 2
  },
  {
    question: "When did the Second World War end? ",
    answers: ["1944", "1945", "1946", "1947"],
    correctIndex: 1
  },
  {
    question: "What’s the name of the famous big clock in London? ",
    answers: ["Times Square", "Big John", "Big Ben", "Big Charlie"],
    correctIndex: 2
  },
  {
    question: "Where was Christopher Columbus born?",
    answers: ["Madrid", "Lisbon", "Milan", "Genoa"],
    correctIndex: 3
  },
  {
    question: "What did the 7 dwarves do for a job?",
    answers: ["Miners", "Farmers", "Carpenters", "Drug Smuglers"],
    correctIndex: 0
  },  
  {
    question: "Who said, “I think, therefore I am”?",
    answers: ["Socrates", "Descartes", "Aristotle", "Donald Trump"],
    correctIndex: 1
  },    
  {
    question: "What’s the smallest type of tree in the world?",
    answers: ["Bonsai", "Pine", "Mango", "Olive Tree"],
    correctIndex: 0
  },
  {
    question: "Which singer’s real name is Stefani Joanne Angelina Germanotta?",
    answers: ["Fergie", "Madonna", "Lady Gaga", "Cher"],
    correctIndex: 2
  },
  {
    question: "How many players are there in a baseball team?",
    answers: ["Nine", "Ten", "Eight", "Seven"],
    correctIndex: 0
  },  
  {
    question: "Which instrument did Louis Armstrong play?",
    answers: ["Piano", "Guitar", "Trumpet", "Tuba"],
    correctIndex: 2
  },
];

function Score(props){
  return(
    <div>
      <div id="question-number">Question number:     {props.questionNumber}   of  {MAX_QUESTIONS}</div>
      <div id="score-group">
        <div className="scores">Correct: {props.correct} </div>
        <div className="scores right">Incorrect: {props.incorrect} </div>
      </div>
    </div>
  )
}

function Answers(props){
  return(
    <div id="answers-group">
      <button id={0} className="noselect" onClick={() => props.handleClick(0)} >{props.answersArray[0]} </button>
      <button id={1} className="noselect"  onClick={() => props.handleClick(1)}>{props.answersArray[1]} </button>
      <button id={2} className="noselect" onClick={() => props.handleClick(2)}>{props.answersArray[2]} </button>
      <button id={3} className="noselect" onClick={() => props.handleClick(3)}>{props.answersArray[3]} </button>
    </div>    
  )  
}

function Question(props){
  return (
    <div id="question">{props.question}</div>
  )
}

class App extends React.Component{  
  constructor(props){
    super(props);    
    this.state = {
      correctAns: 0,
      incorrectAns: 0,
      questionNum: 0,   
      question: "",
      answersArray: [],
      correctAnsIndex: 0,
      gameOver: false,
      firstGame: true,
      //deep copy of object with questions
      questions:  JSON.parse(JSON.stringify(originalQuestions))
    }
    
    this.handleClick = this.handleClick.bind(this);
    this.pickQuestion = this.pickQuestion.bind(this);
    this.newGame = this.newGame.bind(this);
  }
  
  handleClick(id){
    console.log("clicked the id #: " + id);
       
    if(id == this.state.correctAnsIndex){
      this.setState({
        correctAns: this.state.correctAns + 1
      });
    }
    else{
      this.setState({
        incorrectAns: this.state.incorrectAns + 1
      });
    } 
    if(this.state.questionNum >=  MAX_QUESTIONS){
      this.setState({
        gameOver: true
      });
      return;
    }
    setTimeout(this.pickQuestion, 300);
  }
  
  pickQuestion(){
    let idx = Math.floor(Math.random()*this.state.questions.length);
    let questionObj = this.state.questions[idx];
    this.setState({
      questionNum: this.state.questionNum + 1,
      question: questionObj.question,
      answersArray: questionObj.answers,
      correctAnsIndex: questionObj.correctIndex,
      questions: this.state.questions.slice(0,idx).concat(this.state.questions.slice(idx+1,this.state.questions.length))
    });
  }
  
  newGame(){
    this.setState({
       firstGame: false,
       gameOver: false,
       questionNum: 1,
       correctAns: 0,
       incorrectAns: 0,
      //deep copy of object with questions
      questions:  JSON.parse(JSON.stringify(originalQuestions))   
    }, this.pickQuestion() );  
  }
  
 
  
  render(){
    if(this.state.firstGame){
      return(
        <div id="outer">
          <div id="main">
          <Question question="Welcome to Trivia Game" />
            <button onClick={this.newGame}>Start New Game</button>
          <br/><br/>
        </div>
       </div>
      );
    }
    else if(this.state.gameOver){
      return(
        <div id="outer">
          <div id="main">
          <Question question={"GAME OVER"} />
          <button onClick={this.newGame}>Try Again</button>
          <Score correct={this.state.correctAns} incorrect={this.state.incorrectAns} questionNumber={this.state.questionNum}/>
        </div>
       </div>
      );
    }    
    else{
      return(
        <div id="outer">
          <div id="main">
          <Question question={this.state.question} />
          <Answers answersArray={this.state.answersArray} handleClick={this.handleClick} />
          <Score correct={this.state.correctAns} incorrect={this.state.incorrectAns} questionNumber={this.state.questionNum}/>
        </div>
       </div>
      );
    }
    
  }
}

ReactDOM.render(
 <App/>,
 document.getElementById("root")
)

Leave a Reply