Reputation: 37
I'm Building a quiz app which gets the questions and answers from an API, it comprises of the start page and another page to display the questions and answers, I previously set a state start
to switch between the Boolean values to know when to render the questions , but my mapped array of request
isn't rendering on the page with the Question
component.
The App code as well as the Question is below,
I want to make it that on clicking the button, the mapped question is rendered
const [start, setStart] = React.useState(true)
console.log(start)
function renderNextPage() {
setStart(false)
}
const [request, setRequest] = React.useState([])
React.useEffect(() => {
fetch('https://opentdb.com/api.php?amount=5')
.then(res => res.json())
.then(data => setRequest(data.results.map(({
question,
correct_answer,
incorrect_answers
}) => ({
question,
correct_answer,
incorrect_answers
}))))
}, [])
const questionElements = request.map(req => {
return ( <
Question question = {
req.question
}
/>
)
})
return (
start ? < Start handleClick = {
renderNextPage
}
/> : {questionElements}
)
}
// QUestion Component
export default function Question(props) {
return ( <div >
<h1 > {
props.question
}
working </h1>
<
/div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
Upvotes: 1
Views: 40
Reputation: 258
This might happen, because your question elements are not wrapped into a parent component. Hence, you might want to use your question elements like this:
<div>{questionElements}</div?
However, I would recommend using React Router library, when you need multiple pages.
Upvotes: 1