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;
CodePudding user response:
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;
CodePudding user response:
your can add a state 'loading' and add useEffect hook and then use setTimeout there and change the loading state to false after 5seconds. in return section all you need to do is check if loading is false you show the otherwise it will show nothing.
import React, { useEffect, useState } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";
function App() {
const [loading, setLoading] = useState(true);
useEffect(() => {
setTimeout(() => {
setLoading(false);
}, 5000);
}, [])
return (
<div>
{!loading && <Navbar /> }
<Contact />
</div>
);
}
export default App;