I am currently creating a quiz using ReactJS but I want to put in a if/else statement when the quiz has been complete, if the person playing the quiz gets a score below 3 I want it to have a sad face, if above 3 then a happy one, how would I put this into my code?
I have tried so far to incorporate the if statement but not having much luck
Result.js
import React from 'react';
const Result = ({ score, playAgain }) => (
<div className="score-board">
<div className="score">You scored {score} / 5 correct answers!</div>
<button className="playBtn" onClick={playAgain}>
Play again!
</button>
</div>
);
export default Result;
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './assets/style.css';
import quizService from './quizService';
import QuestionBox from './components/QuestionBox';
import Result from './components/Result';
class QuizBee extends Component {
state = {
questionBank: [],
score: 0,
responses: 0,
};
getQuestions = () => {
quizService().then((question) => {
this.setState({
questionBank: question,
});
});
};
computeAnswer = (answer, correctAnswer) => {
if (answer == correctAnswer) {
this.setState({
score: this.state.score + 1,
});
}
this.setState({
responses: this.state.responses < 5 ? this.state.responses + 1 : 5,
});
};
playAgain = () => {
this.getQuestions();
this.setState({
score: 0,
responses: 0,
});
};
componentDidMount() {
this.getQuestions();
}
render() {
return (
<div className="container">
<div className="title">QuizBee</div>
{this.state.questionBank.length > 0 &&
this.state.responses < 5 &&
this.state.questionBank.map(({ question, answers, correct, questionId }) => (
<QuestionBox
question={question}
options={answers}
key={questionId}
selected={(answer) => this.computeAnswer(answer, correct)}
/>
))}
{this.state.responses === 5 ? <Result score={this.state.score} playAgain={this.playAgain} /> : null}
</div>
);
}
}
ReactDOM.render(<QuizBee />, document.getElementById('root'));
Inside the Result.js, you can add the logic as
import React from "react";
const Result = ({score, playAgain}) => (
<div className="score-board">
<div className="score">You scored {score} / 5 correct answers!</div>
{score <=3 ? <SadFace/> : <HappyFace/>}
<button className="playBtn" onClick={playAgain}>
Play again!
</button>
</div>
);
export default Result;
You can do it in your Result component:
import React from "react";
const Result = ({score, playAgain}) => (
<div className="score-board">
<img src={score <= 3 ? "sad.png" : "happy.png" } /> // <----- HERE
<div className="score">You scored {score} / 5 correct answers!</div>
<button className="playBtn" onClick={playAgain}>
Play again!
</button>
</div>
);
export default Result;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.