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>
Contact
</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;
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;
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;
Related
I have two buttons in my code, each trying a different way for redirecting, in one of them i'm trying to use <a>, and the other one I'm trying to use route, but none of them seem to work.
Here's my code:
Component DefineDestino.js:
import React, {useState} from "react"
import { Link, BrowserRouter, Routes, Route } from "react-router-dom"
import CheckOut from "../CheckOut"
export default function DefineDestino(props) {
const [initialValue, setValue] = useState(0)
const increment = () => {
return {
type:'counter/increment'
}
}
function estadosReducer(state, action) {
if (state === 'Rio de Janeiro' && action.type === 'counter/increment') {
setValue(initialValue + 1000)
}
}
return(
<div>
<h1>Valor: {initialValue}</h1>
<button onClick={() => estadosReducer(props.data, increment())}>Efetuar Compra</button>
</div>
)
}
App.js:
import Origem from './components/Origem';
import Destino from './components/Destino'
import './styles/App.css';
import React, {useState} from "react"
import EstadosOrigem from './components/Origem';
import EstadosDestino from './components/Destino';
import DefineDestino from './components/DefineDestino';
import { Link, BrowserRouter as Router, Routes, Route, Switch } from "react-router-dom";
import CheckOut from './CheckOut';
function App() {
return (
<Router>
<div className="App">
<div className="mainContent">
<h1>Escolha um destino.</h1>
< EstadosOrigem ></EstadosOrigem>
< EstadosDestino ></EstadosDestino>
<Routes>
<Route path="/CheckOut" component={CheckOut}></Route>
</Routes>
</div>
</div>
</Router>
);
}
export default App;
The page I'm trying to redirect to CheckOut.js:
function CheckOut() {
return (
<div className="CheckOut">
<div className="mainContent">
<h1>TESTE.</h1>
</div>
</div>
);
}
export default CheckOut;
EDIT: I imported something wrong :facepalm:
Let me first run down what code ive written to get this output then I will tell you the expected output and what im confused about
App.jsx
import React from "react";
import Home from "./components/pages/HomePage";
import store from "./ducks/store";
import { Provider } from "react-redux";
import { BrowserRouter, Route, Switch } from "react-router-dom";
const App = () => {
return (
<BrowserRouter>
<Provider store={store}>
<Switch>
<Route exact path="/" component={Home} />
</Switch>
</Provider>
</BrowserRouter>
);
};
export default App;
Home.jsx
import React, { useEffect } from "react";
import FlexBox from "../../shared/FlexBox";
import BlogPostList from "./SortSettings";
import { useSelector, useDispatch } from "react-redux";
import { fetchAllBlogs } from "../../../ducks/blogs";
import {
getBlogData,
getBlogPosts,
getBlogTags,
} from "../../../ducks/selectors";
import SpinLoader from "../../shared/SpinLoader";
const Home = () => {
const blogData = useSelector((state) => getBlogData(state));
const blogPosts = useSelector((state) => getBlogPosts(state));
const blogTags = useSelector((state) => getBlogTags(state));
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchAllBlogs());
}, [dispatch]);
// TODO: handle if blogData.requestError comes back as true
if (blogData.isLoading || !blogPosts || !blogTags) {
return (
<FlexBox
alignItems="center"
justifyItems="center"
width="100vw"
height="100vh"
>
<SpinLoader />
</FlexBox>
);
}
return (
<FlexBox height="100vh" width="100vw">
<BlogPostList blogPosts={blogPosts} />
</FlexBox>
);
};
export default Home;
BlogPostList.jsx
import React from "react";
import BlogPost from "./BlogPost";
import FlexBox from "../../shared/FlexBox";
const BlogPostList = ({ blogPosts }) => {
return (
<FlexBox flexDirection="column">
Why in the world is this rendering a SortSettings component AHHHHHH!
</FlexBox>
);
};
export default BlogPostList;
Now my question is this why is it that the Home component is rendering a component as showed here https://gyazo.com/8cac1b28bdf72de9010b0b16185943bb what I would expect the Home component to be rendering is a BlogPostList if anyone has an idea help would be appreciated ive been stuck on this for awhile now (im pretty new so this might just be a noob mistake so sorry if its something obvious)
I started to learn React, I'm trying to retrieve data from api, the data is an object with the fields of base, date & rates, without any problem I can print and logout base & date but rates which is an object not.
console.log gives undefined, when trying to iterate is obviously that the object does not exist but in DevTools i can see normal data
Thank you for your help and greetings
Context:
export const ExchangeProvider = props => {
const [lastestExchanges, setLastestExchanges] = useState({})
const fetchLastestExchange = async () => {
try {
await fetch(`https://api.exchangeratesapi.io/latest`).then(data => data.json()).then(data => setLastestExchanges(data))
} catch (err) {
console.log(err)
}
}
useEffect(() => {
fetchLastestExchange()
}, [])
return (
<ExchangeContext.Provider value={[lastestExchanges, setLastestExchanges]}>
{props.children}
</ExchangeContext.Provider>
)
}
Usage:
import React, {useState, useContext} from "react";
import {ExchangeContext} from "../ExchangeContext";
function HomeView() {
const [lastestExchange, setLastestExchange] = useContext(ExchangeContext)
console.log(lastestExchange)
return (
<div className="container">
<p>{lastestExchange.base}</p>
<p>{lastestExchange.date}</p>
{/*<p>{lastestExchange.rates['PLN']}</p>*/}
<ul>
{/*{Object.keys(lastestExchange.rates).map(key => <li>{lastestExchange.rates[key]}</li>)}*/}
</ul>
</div>
)
}
export default HomeView
Provider usage:
import React from 'react';
import HomeView from "./Views/HomeView";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import {ExchangeProvider} from "./ExchangeContext";
function App() {
return (
<ExchangeProvider>
<div className="App container w-full flex h-full">
<Router>
<Switch>
<Route path="/">
<HomeView/>
</Route>
</Switch>
</Router>
</div>
</ExchangeProvider>
);
}
export default App;
You can use react context simpler like this :
// src/ThemeContext.js
import React from 'react';
const ThemeContext = React.createContext(null);
export default ThemeContext;
// src/ComponentA.js
import React from 'react';
import ThemeContext from './ThemeContext';
const A = () => (
<ThemeContext.Provider value="green">
<D />
</ThemeContext.Provider>
);
// src/ComponentD.js
import React from 'react';
import ThemeContext from './ThemeContext';
const D = () => (
<ThemeContext.Consumer>
{value => (
<p style={{ color: value }}>
Hello World
</p>
)}
</ThemeContext.Consumer>
);
I have a java script file called Toolbar.js in which I am trying to call a function that is in my App.js file as the following:
<DrawerToggleButton click={props.drawerClickHandler}/>
The above does not work, it shows "Unresolved variable drawerClickHandler" which I assume means that Toolbar.js can not see the functions in App.js. I have tried this without using props with no results. How can I get this to work?
Also just want to state the program will build and run with no errors, just that the button I am trying to map the function to, does nothing when I click it.
Code below:
Toolbar.js:
import React from 'react';
import './Toolbar.css';
import DrawerToggleButton from '../SideDrawer/DrawerToggleButton'
import '../SideDrawer/DrawerToggleButton';
import sideDrawer from "../SideDrawer/SideDrawer";
const toolbar = props =>(
<header className="toolbar">
<nav className="toolbar_navigation">
<div>
<DrawerToggleButton click={props.drawerClickHandler}/>
</div>
<div className="toolbar_logo">Kleen Portal</div>
<div className="spacer" />
<div className="toolbar_navigation-items">
<ul>
<li>Logout</li>
</ul>
</div>
</nav>
</header>
);
export default toolbar;
App.js:
import React, { useState, useEffect } from "react";
// import logo from './logo.svg';
import './App.css';
import Routes from "./Routes";
import { Auth } from "aws-amplify";
import { Link, withRouter } from "react-router-dom";
// import { Navbar } from "react-bootstrap";
import Toolbar from './components/Toolbar/Toolbar';
import SideDrawer from './components/SideDrawer/SideDrawer';
import Backdrop from './components/Backdrop/Backdrop';
function App(props) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isAuthenticating, setIsAuthenticating] = useState(true);
const [sideDrawerOpen, setIsSideDrawerOpen] = useState(false);
useEffect(() => {
onLoad();
}, [isAuthenticating, isAuthenticated]);
async function onLoad() {
try {
await Auth.currentSession();
setIsAuthenticated(true);
props.history.push("/dashboard");
}
catch(e) {
alert(e);
}
setIsAuthenticating(false);
}
function handleLogout() {
setIsAuthenticated(false);
props.history.push("/login");
}
function drawerToggleClickHandler(){
setIsSideDrawerOpen(!sideDrawerOpen)
}
let sideDrawer;
let backdrop;
let toolBar;
if(isAuthenticated){
toolBar = (
<Toolbar
handleLogout={handleLogout}
drawerClickHandler ={drawerToggleClickHandler}
/>
)
}
if (isAuthenticated && sideDrawerOpen){
sideDrawer = <SideDrawer/>;
backdrop = <Backdrop/>
}
return (
<div className="App container" style={{height: '100%'}}>
{toolBar}
{sideDrawer}
{backdrop}
{/*<Toolbar/>*/}
{/*<SideDrawer/>*/}
{/*<Backdrop/>*/}
<Routes appProps={{ isAuthenticated, setIsAuthenticated }} />
</div>
);
}
export default withRouter(App);
DrawerToggleButton.js:
import React from 'react';
import './DrawerToggleButton.css'
const drawerToggleButton = props => (
<button className="toggle-button" onClick={props.click}>
<div className="toggle-button_line" />
<div className="toggle-button_line" />
<div className="toggle-button_line" />
</button>
);
export default drawerToggleButton;
I expect that console.log('Refresh') runs every time the route changes (switching from Component1 to Component2). But it's only triggering on first render. Why?
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
App.js:
import React, { useEffect } from 'react';
import { Switch, Route } from 'react-router-dom';
import Nav from './Nav';
import Component1 from './Component1';
import Component2 from './Component2';
const App = () => {
useEffect( () => console.log('Refresh'));
return (
[<Switch>
<Route component = {Nav}/>
</Switch>,
<Switch>
<Route exact path = '/component1' component = {Component1}/>
<Route exact path = '/component2' component = {Component2}/>
</Switch>]
);
}
export default App;
Nav.js:
import React from 'react';
import { Link } from 'react-router-dom';
const Nav = () => {
return (
<div>
<Link to = '/component1'>Component 1</Link>
<Link to = '/component2'>Component 2</Link>
</div>
);
}
export default Nav;
Component1.js:
import React from 'react';
const Component1 = () => {
return (
<div>
<p>Hi</p>
</div>
);
}
export default Component1;
Component2.js:
import React from 'react';
const Component2 = () => {
return (
<div>
<p>Bye</p>
</div>
);
}
export default Component2;
The useEffect is not triggered because the App component is not re-rendered, nothing changed in that component (no state or props update).
If you want the App component to re-render when the route change, you can use the withRouter HOC to inject route props, like this :
import { Switch, Route, withRouter } from 'react-router-dom';
const App = () => {
useEffect( () => console.log('Refresh'));
return (...);
}
export default withRouter(App);
Example : https://codesandbox.io/s/youthful-pare-n8p1y
use the key attribute so everytime we render new component (different key)
<Route path='/mypath/:username' exact render= {routeProps =><MyCompo {...routeProps} key={document.location.href} />} />
Use the 2nd argument to useEffect to conditionally apply effect. For example via react-router-dom, you get some properties
const { schoolId, classId } = props
useEffect(() => {
// fetch something here
}, [schoolId, classId)
Here [schoolId, classId acts as the unique identifier for useEffect to trigger.
Using Hooks:
use useLocation and useLayoutEffect get more efficiency:
import { useLocation } from "react-router-dom";
//...
const location = useLocation();
//...
useLayoutEffect(() => {
console.log("location",location)
}, [location])