I am creating a simple web app game and trying to implement a ‘grading’ feature. When the correct answer is typed in the <input>
changes styles. There are a different number of possible answers based on the question’s prompt. To display the right number of <input>
for each question prompt I am using array.map()
. My issue is that when I change the state of a single <input>
the state changes for all of them. How can I change the state of just a single <input>
in a mapped array?
const CountryList = ({countries, firstLetter}) => {
const [answer, checkAnswer] = useState(false);
const handleAnswer = useDebouncedCallback((e) => {
const value = e.target.value;
if (value) {
if (value.length > 4 && countries.includes(value)) {
checkAnswer(true);
}
} else if (!value) {
checkAnswer(false);
}
}, 300);
if (firstLetter == '' || firstLetter == ' '){
return (
<div className={styles.container}>
</div>
)
} else {
return (
<div className={styles.container}>
<div className={styles.numbox}>
<h3 className={styles.countrynum}>
{`There are ${countries.length} countries that start with '${firstLetter.toUpperCase()}'`}
</h3>
</div>
<div className={styles.answerbox}>
{countries.map((country, index, thisValue) => (
<input key={country}
id={`answer-${index}`}
className={`${answer? styles.answercorrect : styles.answer}`}
onChange={handleAnswer} >
</input>
))}
</div>
</div>
)
}
}
I have tried passing this
but have been unsuccessful. I believe it may have to do with how I am calling useDebounceCallback()
but I am unsure.
There is only one state for all of the inputs, so when one changes, they all change. Make the input a separate component so that each input can have its own state. I’d also suggest passing whether the answer is correct via a prop. Then use your custom input component in the map.