I have succeeded in making a quiz app that shows red if the wrong option is clicked and green if the right one is clicked. The thing is that since I am getting the options from an api, I put the correct and incorrect options in an array, gave it state and then mapped over it. This means that if I go to each individual question and pick and option that I would see if it turns red or green, but this unfortunately means that the buttons are managing its own state. I want to create a button at the end of my app, so that after I've picked all my answers for all the questions, it marks all the questions together and not individually like I am doing now but I don't know how.
App.js file:
import {React, useState, useEffect} from 'react'
import './App.css';
import Question from './components/Question'
function App(){
const [getQuestions, setGetQuestions] = useState([])
const [start, setStart] =useState(false)
useEffect(function(){
async function getQuestionsFromApi(){
const res = await fetch(`https://opentdb.com/api.php?amount=5`)
const data = await res.json()
setGetQuestions(data.results)
}
getQuestionsFromApi()
},[])
const displayQuestions = getQuestions.map(
element => <Question
key={element.question}
question = {element.question}
correct_answer = {element.correct_answer}
incorrect_answers ={element.incorrect_answers}
/>
)
function gameStart(){
setStart(true)
}
function checkResult(){
console.log('check result')
}
return(
<>
{start ?
<div>
{displayQuestions}
<button className='result--button' onClick={checkResult}>Check the Answers</button>
</div> :
<div className="home--page">
<h1>Quizzical</h1>
<p>some description if needed</p>
<button className='start' onClick={gameStart} >Start quiz</button>
</div>
}
</>
)
}
export default App
Question.js file:
import {React, useState, useEffect} from 'react'
import './Question.css'
function Question({question, correct_answer, incorrect_answers}){
const [options, setOptions] = useState([])
const [selectedOption, setSelectedOption] = useState()
useEffect(function(){
const arr = [...incorrect_answers, correct_answer]
setOptions(arr)
}, [incorrect_answers, correct_answer])
function handleSelect(element){
if (selectedOption === element && selectedOption === correct_answer) {
return 'select'
} else if (selectedOption === element && selectedOption !== correct_answer) {
return 'wrong'
} else if (element === correct_answer) {
return 'select'
} else {
return 'grey'
}
}
function handleClick(element){
setSelectedOption(element)
}
const displayOptions = options.map(element =>
<button
className= {`${selectedOption && handleSelect(element)}`}
key={element}
onClick={() => handleClick(element)}
disabled={selectedOption}
>
{element}
</button>
)
return(
<>
<div className='question--container'>
<h1>
{question}
</h1>
{displayOptions}
</div>
</>
)
}
export default Question