Skip to content

Instantly share code, notes, and snippets.

@shamimsdp
Forked from igorbenic/answer.js
Created September 5, 2019 09:25
Show Gist options
  • Save shamimsdp/4a425f13f9d57db2b3f8625d4ab92418 to your computer and use it in GitHub Desktop.
Save shamimsdp/4a425f13f9d57db2b3f8625d4ab92418 to your computer and use it in GitHub Desktop.
Building a Quiz with React and WordPress REST API: Question and Answer Components | https://www.ibenic.com/quiz-react-wordpress-question-answer-components
import React, { Component } from 'react';
class Answer extends Component {
constructor(){
super();
// Binding handleChange to 'this'
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
// Using the passed method setAnswer to set the answer.
this.props.setAnswer(e.target.value, this.props.question);
}
render() {
return (
<li className="wpqr-answer">
<label>
<input type="radio" onChange={this.handleChange} name={this.props.question} value={this.props.index} />
{ this.props.answer }
</label>
</li>
);
}
}
export default Answer;
import React, { Component } from 'react';
import Answer from './Answer';
/**
* Question Component.
*
* Rendering the Question with the provided answers.
*/
class Question extends Component {
render() {
let answers = [];
// If we have answers, let's add them.
if ( this.props.question.answers ) {
// For each answer, add an Answer Component.
for( let i = 0; i < this.props.question.answers.length; i++ ) {
// We are pushing the them because each Answer is a React element.
// We can render an array of React elements using JSX.
answers.push( <Answer answer={this.props.question.answers[i]} key={this.props.question.id + '_' + i} index={i} question={this.props.question.id} setAnswer={this.props.setAnswer} /> );
}
if( answers.length > 0 ) {
// If we have answers, let's change the answer to JSX
answers = <ul>{answers}</ul>;
}
}
return (
<div className="wpqr-question">
<h2>{this.props.question.title}</h2>
<div>{this.props.question.content}</div>
{ answers }
</div>
);
}
}
export default Question;
import React, { Component } from 'react';
// Importing the Question Component so we can use it.
import Question from './components/Question';
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 {
// ...
// If we have questions, load the current question.
if ( this.state.questions.length > 0 ) {
const currentQuestion = this.state.questions[ this.state.currentQuestion ];
// Passing the setAnswer method and the current question.
output = <Question setAnswer={this.setAnswer} question={currentQuestion} />;
// ...
}
// ...
}
return (
<div className="App">
{ output }
{ button }
</div>
);
}
}
export default Quiz;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment