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

how to use setTimeout on a react component

This question might be simple to most web developers but I am pretty new and cannot figure out the way to put a settimeout function on what I would like to show on a page. below is the example of the code I would like to add a timeout for.

import React from "react";

function Navbar() {
  return (
    <div className="navbar">
      <h4>
        <a href="#contact">Contact</a>
      </h4>
      <h4>About Me</h4>
    </div>
  );
}

export default Navbar;

and here is my app.jsx which then will be exported to be used in index.js . What I want is to have lets say 5s delay before my Navbar function shows.

import React, { useEffect } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";

function App() {
  return (
    <div>
      <Navbar />
      <Contact />
    </div>
  );
}
export default App;

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 :

You can add setTimeout in your App Component. It should look like this:

import React, { useState, useEffect } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";

function App() {
  const [showNavBar, setShowNavBar] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowNavBar(true);
    }, 5000);
    return () => clearTimeout(timer);
  }, [])

  return (
    <div>
      {showNavBar ? <Navbar /> : null}
      <Contact />
    </div>
  );
}
export default App;
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