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.
JavaScript
x
15
15
1
import React from "react";
2
3
function Navbar() {
4
return (
5
<div className="navbar">
6
<h4>
7
<a href="#contact">Contact</a>
8
</h4>
9
<h4>About Me</h4>
10
</div>
11
);
12
}
13
14
export default Navbar;
15
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.
JavaScript
1
14
14
1
import React, { useEffect } from "react";
2
import Navbar from "./Navbar";
3
import Contact from "./Contact";
4
5
function App() {
6
return (
7
<div>
8
<Navbar />
9
<Contact />
10
</div>
11
);
12
}
13
export default App;
14
Advertisement
Answer
You can add setTimeout
in your App Component. It should look like this:
JavaScript
1
23
23
1
import React, { useState, useEffect } from "react";
2
import Navbar from "./Navbar";
3
import Contact from "./Contact";
4
5
function App() {
6
const [showNavBar, setShowNavBar] = useState(false);
7
8
useEffect(() => {
9
const timer = setTimeout(() => {
10
setShowNavBar(true);
11
}, 5000);
12
return () => clearTimeout(timer);
13
}, [])
14
15
return (
16
<div>
17
{showNavBar ? <Navbar /> : null}
18
<Contact />
19
</div>
20
);
21
}
22
export default App;
23