Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active May 2, 2022 23:15
Show Gist options
  • Save igorbenic/e3194e24cbd16c59be3cf252b174c393 to your computer and use it in GitHub Desktop.
Save igorbenic/e3194e24cbd16c59be3cf252b174c393 to your computer and use it in GitHub Desktop.
Building a Quiz with React and WordPress REST API: Quiz Component | https://www.ibenic.com/quiz-wordpress-rest-api-react-scripts-tool
import React, { Component } from 'react';
import Question from './components/Question';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
constructor() {
super();
this.state = { questions : [], answers: {}, currentQuestion: 0, lastQuestion: false, score: [] };
this.setNextQuestion = this.setNextQuestion.bind(this);
this.fetchQuestions = this.fetchQuestions.bind(this);
this.setAnswer = this.setAnswer.bind(this);
this.getScore = this.getScore.bind(this);
this.fetchQuestions();
}
fetchQuestions() {
fetch(wpqr.rest_url + 'wpqr/v1/questions' ).then( resp => { return resp.json(); } ).then( json => {
this.setState({ questions: json });
if ( json.length < 2 ) { this.setState({ lastQuestion: true });}
});
}
setNextQuestion() {
let currentQuestion = this.state['currentQuestion'];
const questionsCount = this.state['questions'].length;
currentQuestion++;
this.setState({ currentQuestion: currentQuestion });
if( questionsCount === currentQuestion ) {
this.setState( { lastQuestion: true} );
}
}
setAnswer( answer, question ) {
let answers = this.state.answers;
answers[ question ] = answer;
this.setState({ answers: answers });
}
getScore() {
// Building the QueryString
var queryString = [];
for(var answer in this.state.answers ) {
queryString.push(encodeURIComponent('answers[' + answer + ']') + "=" + encodeURIComponent(this.state.answers[answer]));
}
fetch(wpqr.rest_url + 'wpqr/v1/result', {
method: 'POST',
headers: { "Content-type": "application/x-www-form-urlencoded"},
body: queryString.join('&'),
}).then( resp => { return resp.json(); } ).then( json => console.log(json) );
}
render() {
let output = 'Loading Questions...';
let button = '';
if( this.state.score.length ) {
output = 'SCORE';
} else {
let buttonDisabled = true;
if ( this.state.questions.length > 0 ) {
const currentQuestion = this.state.questions[ this.state.currentQuestion ];
output = <Question setAnswer={this.setAnswer} question={currentQuestion} />;
if( this.state.answers.hasOwnProperty( currentQuestion.id ) ) {
buttonDisabled = false;
}
}
button = <button disabled={buttonDisabled} onClick={this.setNextQuestion} type="button">Next Question</button>;
if( this.state.lastQuestion ) {
button = <button disabled={buttonDisabled} onClick={this.getScore} type="button">Get Score</button>;
}
}
return (
<div className="App">
{ output }
{ button }
</div>
);
}
}
export default Quiz;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Quiz from './Quiz';
ReactDOM.render(<Quiz />, document.getElementById('wpqr'));
import React, { Component } from 'react';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
constructor() {
super();
this.state = {
questions : [], // All available questions.
answers: {}, // Answers from the user.
currentQuestion: 0, // Current Question.
lastQuestion: false, // Is the current Question also the last one?
score: [] // Score after submitting answers.
};
// Bind 'this' so we can use this inside that method.
this.fetchQuestions = this.fetchQuestions.bind(this);
// Fetch all the questions.
this.fetchQuestions();
}
// ...
}
export default Quiz;
import React, { Component } from 'react';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
constructor() {
super();
this.state = {
questions : [], // All available questions.
answers: {}, // Answers from the user.
currentQuestion: 0, // Current Question.
lastQuestion: false, // Is the current Question also the last one?
score: [] // Score after submitting answers.
};
// Bind 'this' so we can use this inside that method.
this.fetchQuestions = this.fetchQuestions.bind(this);
// Fetch all the questions.
this.fetchQuestions();
// Bind 'this' to method setNextQuestion()
this.setNextQuestion = this.setNextQuestion.bind(this);
}
// ...
}
export default Quiz;
import React, { Component } from 'react';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
constructor() {
super();
this.state = {
questions : [], // All available questions.
answers: {}, // Answers from the user.
currentQuestion: 0, // Current Question.
lastQuestion: false, // Is the current Question also the last one?
score: [] // Score after submitting answers.
};
// Bind 'this' so we can use this inside that method.
this.fetchQuestions = this.fetchQuestions.bind(this);
// Fetch all the questions.
this.fetchQuestions();
// Binding the question for setting an answer and getting the score.
this.setAnswer = this.setAnswer.bind(this);
this.getScore = this.getScore.bind(this);
}
// ...
}
export default Quiz;
import React, { Component } from 'react';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
// ...
fetchQuestions() {
fetch(wpqr.rest_url + 'wpqr/v1/questions' ).then( resp => { return resp.json(); } ).then( json => {
this.setState({ questions: json });
if ( json.length < 2 ) { this.setState({ lastQuestion: true });}
});
}
// ...
}
export default Quiz;
import React, { Component } from 'react';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
// ...
/**
* Setting the Next Question
*/
setNextQuestion() {
// Get the current question number
let currentQuestion = this.state['currentQuestion'];
// Get the number of questions
const questionsCount = this.state['questions'].length;
currentQuestion++;
// If the number of question is bigger than the index of the current Question
// Because array items start with 0 not 1
if ( questionsCount > currentQuestion ) {
// Set the current question.
this.setState({ currentQuestion: currentQuestion });
// Is this also the last question?
if( questionsCount === currentQuestion +1 ) {
this.setState( { lastQuestion: true } );
}
}
}
// ...
}
export default Quiz;
import React, { Component } from 'react';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
// ...
render() {
let output = 'Loading Questions...';
let button = '';
if( this.state.score.length ) {
output = 'This will be a Score Component';
} else {
// The button is disabled by default.
let buttonDisabled = true;
// If we have questions, load the current question.
if ( this.state.questions.length > 0 ) {
const currentQuestion = this.state.questions[ this.state.currentQuestion ];
output = 'This will be a Question Component';
// If we have an answer for this question,
// button is not disabled anymore so we can continue with the quiz
if( this.state.answers.hasOwnProperty( currentQuestion.id ) ) {
buttonDisabled = false;
}
}
button = <button disabled={buttonDisabled} onClick={this.setNextQuestion} type="button">Next Question</button>;
// If the current question is also the last one, we show the 'Get Score' button instead.
if( this.state.lastQuestion ) {
button = <button disabled={buttonDisabled} onClick={this.getScore} type="button">Get Score</button>;
}
}
return (
<div className="App">
{ output }
{ button }
</div>
);
}
}
export default Quiz;
import React, { Component } from 'react';
import './Quiz.css';
/* global wpqr */
class Quiz extends Component {
// ...
/**
* Setting the answer of the current question.
* @param integer answer The order of the chosen answer
* @param integer question The Question ID.
*/
setAnswer( answer, question ) {
let answers = this.state.answers;
answers[ question ] = answer;
this.setState({ answers: answers });
}
/**
* Getting the Score for the answers
*/
getScore() {
console.log('This will get the scores for:');
console.log( this.state.answers );
}
// ...
}
export default Quiz;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment