Home > Enterprise >  React js navigating multipage with single
React js navigating multipage with single

Time:07-20

My question is that possible that we can travers in single page with different content using single button

I am creating quiz in react there is 4 quiz for selection. as per shown in image, after selecting quiz i want to show content of that quiz in same page, even after selecting different quiz option i want to show selected quiz content in same page

CodePudding user response:

One of the solutions could be:

  • In you main component use state to store which quiz is active
  • In the same component, check which quiz is selected and render the right quiz component.

A simple example

export function Main()  {
  const [quiz, setQuiz] = useState(null /* or the default quiz, if any */)

  function getQuiz() {
    switch(quiz) {
      case 'A':
        return <QuizA />
      case 'B':
        return <QuizB />
      case 'C':
        return <QuizC />
      default:
        // Render nothing when no quiz is set
        return <></> 
    }
  }

  return (
    <>
      <div>
        <button onClick={() => setQuiz('A')}>Quiz A</button>
        <button onClick={() => setQuiz('B')}>Quiz B</button>
        <button onClick={() => setQuiz('C')}>Quiz C</button>
      </div>
      <div>
         {getQuiz()}
      </div>
    </>
  )
}

CodePudding user response:

You can conditionally render your components using a switch case or a if else and lazy loading if that helps your use case. https://stackoverflow.com/a/52618847/19581096

  • Related