I have a little quiz where u should guess the country. It starts with an image by clicking the "Next" button. Now I wanna show hint after hint, when I click on "Next Hint". Right now, when I click on "Next Hint", every hint is shown at the same time. Im not sure how to give hints one after another (first area, then population…etc).
import React from 'react'
import "./Geography.css"
import {useState} from "react";
import country from "../Countries.json"
function Geography() {
const [show, setShow] = useState(false);
const [image, setImage] = useState();
const [name, setName] = useState();
const [area, setArea] = useState();
const [population, setPopulation] = useState();
const [countryList, setCountryList] = useState(country);
const handleStart = () => {
let random = Math.floor(Math.random() * country.length);
setImage(countryList[random].image);
setArea(countryList[random].area);
setPopulation(countryList[random].population);
}
return (
<div className='geo'>
<h1>Guess the Country</h1>
<div className='button'>
<button className='button__start' onClick={handleStart}>Next</button>
<button className='button__start' onClick={()=>setShow(!show)}>Next Hint</button>
</div>
<div className='pic'>
<img src={image} />
{show && <h1>{area}</h1>}
{show && <h1>{population}</h1>}
</div>
</div>
)
}
2
Answers
To show hints one after another when clicking the "Next Hint" button, you can use an additional state variable to keep track of the hint index. Each time the button is clicked, you increment the hint index and display the corresponding hint based on the current index.
Here’s an updated version of your code with the changes:
In this updated code, a new state variable hintIndex is introduced to keep track of the current hint index. Each time the "Next Hint" button is clicked, the handleNextHint function is called, which increments the hintIndex by 1. Then, in the rendering part, the hints are displayed based on the current value of hintIndex. Only when hintIndex is greater than or equal to 1, the area hint is shown. Similarly, when hintIndex is greater than or equal to 2, the population hint is shown.
This way, the hints will be displayed one after another as you click the "Next Hint" button.
I don’t know if this is what you want, but the most simple solution is as simple as that :
becomes