I am trying to add a hint option to my quiz app. If the 50/50 button is clicked I want to render the newAnswers array. else I want to render the shuffledAnswers array.
when I run this code I get
TypeError: Cannot read properties of null (reading 'useState')
What am I doing wrong here?
import React from "react";
import { useState } from "react/cjs/react.production.min";
import Card from "../UI/Card";
import "./DisplayQuestion.css";
import ProgressBar from "./Progress";
const DisplayQuestion = (props) => {
/*I used dangerouslySetInnerHTML to fix the quotes gibberish problem */
const [hint, setHint] = useState(false);
console.log("hint: ", hint);
let notBoolean = false;
const newAnswers = [
props.data.correct_answer,
props.data.incorrect_answers[0],
];
/*Helper functions */
// shuffles the answers
let shuffledAnswers = [
props.data.correct_answer,
...props.data.incorrect_answers,
].sort(() => Math.random() - 0.5);
if (shuffledAnswers.length > 2) {
notBoolean = true;
console.log("notBoolean");
}
const answersHintHandler = () => {
setHint(true);
console.log("hint: ", hint);
console.log(newAnswers);
};
let progress = Math.round((props.score / props.numOfQuestions) * 100);
return (
<div>
<h3 >Difficulty: {props.diff}</h3>
<div classname="Questions">
<Card>
<ProgressBar bgcolor="#99ccff" progress={progress} height={30} />
<h2>
Questions {props.index}/{props.numOfQuestions}
</h2>
<h2
className="question-text"
dangerouslySetInnerHTML={{
__html: props.data.question,
}}
/>
<ul>
{notBoolean ? (
<button onClick={answersHintHandler}>50/50</button>
) : (
<p></p>
)}
{hint
? newAnswers.map((answer) => {
return (
<li
onClick={() => props.handler(answer)}
dangerouslySetInnerHTML={{
__html: answer,
}}
></li>
);
})
: shuffledAnswers.map((answer) => {
return (
<li
onClick={() => props.handler(answer)}
dangerouslySetInnerHTML={{
__html: answer,
}}
></li>
);
})}
</ul>
</Card>
</div>
</div>
);
};
export default DisplayQuestion;
CodePudding user response:
Replace 1st and 2nd line with
import React, { useState } from 'react'
CodePudding user response:
You are importing useState from the wrong path x)
import { useState } from "react/cjs/react.production.min";
Care the automatic imports haha