Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display two React components one after another

I have a quiz game where you have to remember the items(from images) and answer the quiz. First,4 images are shown with the time interval of 2 secs and after that the 4 quiz will start. I have Images component(which display images in intervals) and Quiz component. I want to hide the images component once it is finished and show the quiz. I tried to do it using conditional rendering but its not working.

import { useState, useEffect } from "react";

import Quiz from "./Quiz.js";
import Images from "./Images";
import "./styles.css";

const images = [
  "https://picsum.photos/id/1/200/300",
  "https://picsum.photos/id/2/200/300",
  "https://picsum.photos/id/3/200/300",
  "https://picsum.photos/id/4/200/300"
];

export default function App() {
  const [image, setImage] = useState();
  const [showImages, setShowImages] = useState(true);
  const [showQuestions, setShowQuestions] = useState(false);

  useEffect(() => {
    const function1 = () =>
      images.forEach((c, i) => setTimeout(() => setImage(c), i * 2000));

    function1();
    //setShowImages(false);
  }, []);

  return (
    <div className="App">
      <div className="screen">
        {showImages && <Images image={image} />}
        {showQuestions && <Quiz />}
      </div>
    </div>
  );
}

codesanbox link: https://codesandbox.io/s/elastic-snowflake-qo1nz7?file=/src/App.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I hope this will solve your problem.

  useEffect(() => {
    setShowQuestions(false);
    setShowImages(true);
    const function1 = () =>
      images.forEach((c, i) => setTimeout(() => setImage(c), i * 2000));

    function1();
    setTimeout(() => {
      setShowImages(false);
      setShowQuestions(true);
    }, images.length * 2000);
  }, [])

Here’s a codesandbox link https://codesandbox.io/s/wizardly-elion-4dh35s?file=/src/App.js

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading