1

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.