Problems with navigation - javascript

I have this router animation working on page load but when I use the navbar to navigate it changes the web address but the pages don't change or take extremely long to change.
import React, { useContext } from "react";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, __RouterContext } from "react-router-dom";
import { useTransition, animated } from "react-spring";
import "assets/scss/material-kit-react.scss?v=1.4.0";
// pages for this product
import LandingPage from "views/LandingPage/LandingPage.jsx";
import ProfilePage from "views/ProfilePage/ProfilePage.jsx";
var hist = createBrowserHistory();
const App = () => {
const { location } = useContext(__RouterContext);
const transitions = useTransition(location, location => location.pathname, {
from: { opacity: 0, transform: "translate(100%,0)" },
enter: { opacity: 1, transform: "translate(0%,0)" },
leave: { opacity: 0, transform: "translate(-50%,0)" }
});
return (
<>
{transitions.map(({ item, props, key }) => (
<animated.div key={key} style={props}>
<Router history={hist}>
<Switch location={item}>
<Route path="/profile-page" component={ProfilePage} />
<Route path="/" component={LandingPage} />
</Switch>
</Router>
</animated.div>
))}
</>
);
};
export default App;
This is how my NavLink is structured
<Link
exact
to="/profile-page"
className={classes.link}
activeClassName="active"
>

I tried to recreate your problem. I think your problem could be, that you use Router outside and inside the App as well. Because useContext would not work without an outer router.
So the solution is to remove router from the render of the app. Here is my full working example:
import React, { useContext } from 'react';
import { createBrowserHistory } from 'history';
import {
Route,
Switch,
Link,
__RouterContext,
BrowserRouter
} from 'react-router-dom';
import { useTransition, animated } from 'react-spring';
import ReactDOM from 'react-dom';
function App() {
return (
<BrowserRouter>
<Home />
</BrowserRouter>
);
}
// pages for this product
const LandingPage = () => {
return (
<div>
<h1>LandingPage</h1>
<Link to="/profile-page">profile</Link>
</div>
);
};
const ProfilePage = () => {
return (
<div>
<h1>Profile</h1>
<Link to="/">main</Link>
</div>
);
};
const Home = () => {
const { location } = useContext(__RouterContext);
const transitions = useTransition(location, location => location.pathname, {
from: {
position: 'absolute',
width: '100%',
opacity: 0,
transform: 'translate(100%,0)'
},
enter: { opacity: 1, transform: 'translate(0%,0)' },
leave: { opacity: 0, transform: 'translate(-50%,0)' }
});
return (
<>
{transitions.map(({ item, props, key }) => (
<animated.div key={key} style={props}>
<Switch location={item}>
<Route path="/profile-page" component={ProfilePage} />
<Route path="/" component={LandingPage} />
</Switch>
</animated.div>
))}
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
export default App;
You can try it here: https://codesandbox.io/s/sleepy-wozniak-b07jp

Related

React app display blank page without any compilation error

I am not sure what went wrong with my react app below, it compile successfully without error but doesn't show anything (just show a blank page). Can anyone point out what went wrong with my code? Sorry I am new to react.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'
import { BrowserRouter } from 'react-router-dom'
import App from './App';
ReactDOM.render((
// <Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
// </Provider>
), document.getElementById('root'))
App.js
import { BrowserRouter as Router, Route, Link, NavLink } from "react-router-dom";
import Home from "./components/Home";
import NewBuilding from "./components/NewBuilding";
import React, { Component } from "react";
import Web3 from 'web3';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import Typography from '#material-ui/core/Typography';
import "./App.css";
import { useEffect, useState } from 'react';
function App() {
const [currentAccount, setCurrentAccount] = useState(null);
const checkWalletIsConnected = async () => {
const { ethereum } = window;
if (!ethereum) {
console.log("Make sure you have Metamask installed!");
return;
} else {
console.log("Wallet exists! We're ready to go!")
}
const accounts = await ethereum.request({ method: 'eth_accounts' });
if (accounts.length !== 0) {
const account = accounts[0];
console.log("Found an authorized account: ", account);
setCurrentAccount(account);
} else {
console.log("No authorized account found");
}
}
const connectWalletHandler = async () => {
const { ethereum } = window;
if (!ethereum) {
alert("Please install Metamask!");
}
try {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
console.log("Found an account! Address: ", accounts[0]);
setCurrentAccount(accounts[0]);
} catch (err) {
console.log(err)
}
}
const connectWalletButton = () => {
return (
<button onClick={connectWalletHandler} className='cta-button connect-wallet-button'>
Connect Wallet
</button>
)
}
useEffect(() => {
checkWalletIsConnected();
}, [])
return (
<div>
<Router>
<AppBar position="static" color="default" style={{ margin: 0 }}>
<Toolbar>
<Typography variant="h6" color="inherit">
<NavLink className="nav-link" to="/">Home</NavLink>
</Typography>
<NavLink className="nav-link" to="/new/">New</NavLink>
</Toolbar>
</AppBar>
<Route path="/" exact component={Home} />
<Route path="/new/" component={NewBuilding} />
</Router>
</div>
)
}
export default App;
My Home.js is residing in a components folder
The folder structure is as below
Home.js
import React, { useState, useEffect } from "react";
import { makeStyles } from '#material-ui/core/styles';
import Web3 from 'web3'
const useStyles = makeStyles(theme => ({
button: {
margin: theme.spacing(1),
},
input: {
display: 'none',
},
}));
const Home = () => {
const classes = useStyles();
const [ contract, setContract] = useState(null)
const [ accounts, setAccounts ] = useState(null)
const [ funds, setFunds ] = useState([])
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
useEffect(() => {
}, []);
return (
<div><h2>Home</h2></div>
)
}
export default Home;
Your Route component should have the prop element instead of component, see the migration guide.
<Route path="/" exact element={<Home />} />
In App.js you're wrapping your components again in a Router. Instead you should wrap your Route components in a Routes.
import { Routes, Route, Link, NavLink } from "react-router-dom";
...
<div>
<AppBar position="static" color="default" style={{ margin: 0 }}>
<Toolbar>
<Typography variant="h6" color="inherit">
<NavLink className="nav-link" to="/">
Home
</NavLink>
</Typography>
<NavLink className="nav-link" to="/new/">
New
</NavLink>
</Toolbar>
</AppBar>
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/new/" element={<NewBuilding />} />
</Routes>
</div>

Cannot update a component while rendering a different component)

Im using React 18, React Router 6 and React Auth Kit 2.7
I tried to do login page, as showed in example for RAK link
But i getting this error
Code for Login Component JSX
import React from "react"
import axios from "axios"
import { useIsAuthenticated, useSignIn } from "react-auth-kit"
import { useNavigate, Navigate } from "react-router-dom"
const SignInComponent = () => {
const isAuthenticated = useIsAuthenticated()
const signIn = useSignIn()
const navigate = useNavigate()
const [formData, setFormData] = React.useState({ login: "", password: "" })
async function onSubmit(e) {
e.preventDefault()
axios.post("http://localhost:3030/api/auth/login", formData).then((res) => {
if (res.status === 200) {
if (
signIn({
token: res.data.token,
expiresIn: res.data.expiresIn,
tokenType: "Bearer",
authState: res.data.authUserState,
})
) {
navigate("/profile")
console.log("logged in")
} else {
//Throw error
}
} else {
console.log("da duck you want")
}
})
}
console.log(isAuthenticated())
if (isAuthenticated()) {
// If authenticated user, then redirect to his profile
return <Navigate to={"/profile"} replace />
} else {
return (
<form onSubmit={onSubmit} className="flex flex-col w-96 p-2">
<input
className="text-black mt-2"
type={"login"}
onChange={(e) => setFormData({ ...formData, login: e.target.value })}
/>
<input
className="text-black mt-2"
type={"password"}
onChange={(e) =>
setFormData({ ...formData, password: e.target.value })
}
/>
<button type="submit">Submit</button>
</form>
)
}
}
export default SignInComponent
Routes.jsx
// system
import React from 'react'
import { RequireAuth } from 'react-auth-kit'
import { BrowserRouter, Route, Routes } from 'react-router-dom'
// pages
import DeveloperPage from "../pages/Dev.page";
import MainPage from "../pages/Main.page";
import ProfilePage from "../pages/profile/Profile.page";
import LoginPage from "../pages/Auth/Login.page.auth"
import RegisterPage from "../pages/Auth/Register.page.auth"
// components
// logic
const RoutesComponent = () => {
return (
<BrowserRouter>
<Routes>
{/* main */}
<Route path={"/"} element={<MainPage />} />
{/* Authentication */}
<Route path={"/login"} element={<LoginPage />} />
<Route path={"/register"} element={<RegisterPage />} />
{/* Developer */}
<Route path={"/dev"} element={<DeveloperPage />} />
{/* Other */}
<Route path={"/profile"} element={
<RequireAuth loginPath={"/login"}>
<ProfilePage />
</RequireAuth>
} />
</Routes>
</BrowserRouter>
);
};
export default RoutesComponent;
Profile.jsx
import React, { useState } from 'react'
export default function App() {
return (
<div className="wrapper">
<h1>Profile</h1>
</div>
);
}
Im already tried searching this error all over stackoverflow, github issues and link that provided by error but still dont understand how to fix error in my example
Updated:
App.jsx
import React from "react";
import { AuthProvider } from "react-auth-kit";
import RoutesComponent from "./routes/router";
import "./index.css";
function App() {
return (
<AuthProvider authName={"_auth"} authType={"localstorage"}>
<RoutesComponent />
</AuthProvider>
);
}
export default App;
Have you put your application inside AuthProvider? https://github.com/react-auth-kit/react-auth-kit/blob/master/examples/create-react-app/src/App.js

how to Route parent to child component in react router dom

I have an admin dashboard you can check to hear
I want to that if the admin clicks in user(You can see in the screenshot) then it will render the user page and other pages I trying to implement Nested Routeing But not working please if anyone can help it will be appreciated
if someone knows how to render child components and implement them in App.js Please Tell me
Admin.js
import React from 'react'
import { useState } from "react";
import "../AllStyle.css";
import {FaHouseUser, FaTasks, FaUser, FaBars} from "react-icons/fa"
import { NavLink } from 'react-router-dom'
import { AnimatePresence, motion } from "framer-motion";
import SidebarMenu from './SidebarMenu'
const routes = [
{
path: "/user",
name: "Users",
icon: <FaHouseUser />,
},
{
path: "/project",
name: "Project",
icon: <FaTasks />,
},
{
path: "/login",
name: "Logout",
icon: <FaUser />,
},
];
const Admin = ({ children }) => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);
const showAnimation = {
hidden: {
width: 0,
opacity: 0,
transition: {
duration: 0.5,
},
},
show: {
opacity: 1,
width: "auto",
transition: {
duration: 0.5,
},
},
};
return (
<>
<div className="main-container">
<motion.div
animate={{
width: isOpen ? "200px" : "45px",
transition: {
duration: 0.5,
type: "spring",
damping: 10,
},
}}
className={`sidebar `}
>
<div className="top_section">
<AnimatePresence>
{isOpen && (
<motion.h1
variants={showAnimation}
initial="hidden"
animate="show"
exit="hidden"
className="logo"
>
Evalue portal
</motion.h1>
)}
</AnimatePresence>
<div className="bars">
<FaBars onClick={toggle} />
</div>
</div>
<section className="routes">
{routes.map((route, index) => {
if (route.subRoutes) {
return (
<SidebarMenu
setIsOpen={setIsOpen}
route={route}
showAnimation={showAnimation}
isOpen={isOpen}
/>
);
}
return (
<NavLink
to={route.path}
key={index}
className="link"
// activeClassName="active"
>
<div className="icon">{route.icon}</div>
<AnimatePresence>
{isOpen && (
<motion.div
variants={showAnimation}
initial="hidden"
animate="show"
exit="hidden"
className="link_text"
>
{route.name}
</motion.div>
)}
</AnimatePresence>
</NavLink>
);
})}
</section>
</motion.div>
<main>{children}</main>
</div>
</>
);
};
export default Admin
App.js
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import Navbar from './components/Navbar';
import Contact from './components/Contact';
import Service from './components/Service'
import Login from './components/Login';
// Redirect to their dashboar
import Admin from './components/dashboard/admin/Admin';
import Employee from './components/dashboard/Employee';
import Publisher from './components/dashboard/Publisher';
//Toast error message show
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import Reset from './components/Reset';
import Newpassword from './components/Newpassword';
//admin Routes
import User from './components/dashboard/admin/pages/User'
import Project from './components/dashboard/admin/pages/Project'
function App() {
return (
<div>
<Router>
<Navbar/>
<Routes>
<Route exact path="/" element={<Home/>} />
<Route exact path="/service" element={<Service/>} />
<Route exact path="/contact" element={<Contact/>} />
<Route exact path="/login" element={<Login/>} />
<Route exact path="/reset" element={<Reset/>} />
<Route exact path="/reset/:token" element={<Newpassword/>} />
{/* Redirect to their dashboard */}
<Route exact path="/admin" element={<Admin/>} />
<Route exact path="/employee" element={<Employee/>} />
<Route exact path="/publisher" element={<Publisher/>} />
</Routes>
</Router>
{/* admin routes*/}
<Router>
{/* <Admin> For the admin children route to render children*/}
<Routes>
<Route path="/user" element={<User />} />
<Route path="/project" element={<Project />} />
</Routes>
{/* </Admin> */}
</Router>
<ToastContainer
position="top-right"
autoClose={4000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
/>
</div>
);
}
export default App;
You can use Outlet component.
Example of implementation:
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import { AuthProvider } from "./utils/context/auth";
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
app.js
import React from "react";
import { Route, Routes } from "react-router-dom";
import { useAuth } from "./utils/context/auth";
import "react-toastify/dist/ReactToastify.css";
import "./index.css";
import LoginPage from "./app/pages/Auth/Login";
import NotFoundPage from "./app/pages/NotFound/NotFound";
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const App = () => {
const { checkingSession, isAuthenticated } = useAuth();
if (checkingSession) {
return <Loading />;
}
return (
<>
<Navbar />
<Routes>
{checkingSession || !isAuthenticated ? (
<Route path={"/"} element={<LoginPage />} />
) : (
<Route path="/admin" element={<Layout />}>
<Route path={"/admin"} element={<Dashboard />} />
<Route path={"/admin/project"} element={<Project />} />
</Route>
)}
<Route path={"/*"} element={<NotFoundPage />} />
<ToastContainer
position="top-right"
autoClose={4000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
/>
</Routes>
</>
);
};
export default App;
layout.js
import React from 'react'
import { useState } from "react";
import "../AllStyle.css";
import {FaHouseUser, FaTasks, FaUser, FaBars} from "react-icons/fa"
import { NavLink } from 'react-router-dom'
import { AnimatePresence, motion } from "framer-motion";
import SidebarMenu from './SidebarMenu'
import { Outlet } from "react-router-dom";
// The outlet component
const routes = [
{
path: "/user",
name: "Users",
icon: <FaHouseUser />,
},
{
path: "/project",
name: "Project",
icon: <FaTasks />,
},
{
path: "/login",
name: "Logout",
icon: <FaUser />,
},
];
const Private = ({ children }) => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);
const showAnimation = {
hidden: {
width: 0,
opacity: 0,
transition: {
duration: 0.5,
},
},
show: {
opacity: 1,
width: "auto",
transition: {
duration: 0.5,
},
},
};
return (
<>
<div className="main-container">
<motion.div
animate={{
width: isOpen ? "200px" : "45px",
transition: {
duration: 0.5,
type: "spring",
damping: 10,
},
}}
className={`sidebar `}
>
<div className="top_section">
<AnimatePresence>
{isOpen && (
<motion.h1
variants={showAnimation}
initial="hidden"
animate="show"
exit="hidden"
className="logo"
>
Evalue portal
</motion.h1>
)}
</AnimatePresence>
<div className="bars">
<FaBars onClick={toggle} />
</div>
</div>
<section className="routes">
{routes.map((route, index) => {
if (route.subRoutes) {
return (
<SidebarMenu
setIsOpen={setIsOpen}
route={route}
showAnimation={showAnimation}
isOpen={isOpen}
/>
);
}
return (
<NavLink
to={route.path}
key={index}
className="link"
// activeClassName="active"
>
<div className="icon">{route.icon}</div>
<AnimatePresence>
{isOpen && (
<motion.div
variants={showAnimation}
initial="hidden"
animate="show"
exit="hidden"
className="link_text"
>
{route.name}
</motion.div>
)}
</AnimatePresence>
</NavLink>
);
})}
</section>
</motion.div>
<main>
<Outlet /> // The outlet component
</main>
</div>
</>
);
};
export default Private
Basically the Outlet will render the routes you put inside the /admin route. More info in this link

Nested Router in ReactJS - Show blank page on refresh

I am a beginner in ReactJS and React Router and I am having some issues with my nested router.
For my main router in App.js, things work well. So I can visit my landing page (/), login page (/login), and register page (/register). And once I reach this page, if I do a manual refresh on my Chrome Browser (ctrl r), the page refresh and render accordingly.
Below is my App.js
import React from "react";
import { Router, Switch } from "react-router-dom";
import Login from "./components/Login";
import Register from "./components/Register";
import Dashboard from "./components/Dashboard";
import DynamicLayout from './router/DynamicLayout';
import LandingPage from './components/homepage/LandingPage';
import { history } from "./helpers/history";
const App = () => {
return (
<Router history={history}>
<div className="App">
<Switch>
<DynamicLayout
exact
path="/"
component={LandingPage}
layout="LANDING_NAV"
/>
<DynamicLayout
exact
path="/login"
component={Login}
layout="LOGIN_PAGE"
/>
<DynamicLayout
exact
path="/register"
component={Register}
layout="REGISTER_PAGE"
/>
<DynamicLayout
path="/dashboard"
component={Dashboard}
layout="DASHBOARD_PAGE"
/>
</Switch>
</div>
</Router>
);
};
export default App;
Below is my DynamicLayout.js
import React from "react";
import { BrowserRouter as Route, Switch } from "react-router-dom";
import Login from "../components/Login";
import Register from "../components/Register";
const DynamicLayout = (props) => {
const { component: RoutedComponent, layout, ...rest } = props;
const actualRouteComponent = <RoutedComponent {...props} />;
switch (layout) {
case "LANDING_NAV": {
return <div>{actualRouteComponent}</div>;
}
case "LOGIN_PAGE": {
return <div>{actualRouteComponent}</div>;
}
case "REGISTER_PAGE": {
return <div>{actualRouteComponent}</div>;
}
case "DASHBOARD_PAGE": {
return <div>{actualRouteComponent}</div>;
}
default: {
return (
<div>
<h2>Default Nav</h2>
{actualRouteComponent}
</div>
);
}
}
};
export default DynamicLayout;
The issue is with my nested router which is in my Dashboard component. Basically, once a admin user logged in, they will be shown the admin dashboard.
Below is my Dashboard component.
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { history } from "../helpers/history";
import { useHistory } from 'react-router-dom';
import {
BrowserRouter as Router,
Route,
Switch,
} from "react-router-dom";
import { logout } from "../actions/auth";
import AdminSideNavBar from "../components/admin/AdminSideNavBar";
import AdminManageUsers from "./admin/AdminManageUsers";
import AdminPendingApprovalUsers from "../components/admin/AdminPendingApprovalUsers";
import AdminDeactivatedUsers from "./admin/AdminDeactivatedUsers";
import AdminRegisterInternalUsers from "./admin/AdminRegisterInternalUsers";
import AdminLogs from "../components/admin/AdminLogs";
import BrokerSideNavBar from "../components/broker/BrokerSideNavBar";
import ShareholderSideNavBar from "../components/shareholder/ShareholderSideNavBar";
import Login from "../components/Login"
import AdminActivatedUsers from "./admin/AdminActivatedUsers";
const Dashboard = () => {
const [showAdminDashboard, setShowAdminDashboard] = useState(false);
const [showBrokerDashboard, setShowBrokerDashboard] = useState(false);
const [showShareholderDashboard, setShowShareholderDashboard] =
useState(false);
const { user: currentUser } = useSelector((state) => state.auth);
const dispatch = useDispatch();
useEffect(() => {
if (currentUser) {
setShowAdminDashboard(currentUser.roles.includes("ROLE_ADMIN"));
setShowBrokerDashboard(currentUser.roles.includes("ROLE_BROKER"));
setShowShareholderDashboard(
currentUser.roles.includes("ROLE_SHAREHOLDER")
);
}
}, [currentUser]);
const logOut = () => {
dispatch(logout());
};
let history = useHistory();
return (
<div>
{showAdminDashboard && (
<Router history= {history}>
<div className="wrapper">
<AdminSideNavBar />
<Switch>
<Route exact path="/dashboard" component={AdminPendingApprovalUsers} />
<Route exact path="/logs" component={AdminLogs} />
<Route exact path="/manageusers" component={AdminManageUsers} />
<Route exact path="/activeusers" component={AdminActivatedUsers} />
<Route exact path="/deactivatedusers" component={AdminDeactivatedUsers} />
<Route exact path="/registerinternalusers" component={AdminRegisterInternalUsers} />
</Switch>
</div>
</Router>
)}
{showBrokerDashboard && <BrokerSideNavBar />}
{showShareholderDashboard && <ShareholderSideNavBar />}
</div>
);
};
export default Dashboard;
With my side nav bar (AdminSideNavbar component), I can navigate to the various pages. Like /logs, /manageusers, /activeusers etc.
Below is my AdminSideNavBar component
import React from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { logout } from "../../actions/auth";
import {
CDBSidebar,
CDBSidebarContent,
CDBSidebarFooter,
CDBSidebarHeader,
CDBSidebarMenu,
CDBSidebarMenuItem,
} from "cdbreact";
import { NavLink } from "react-router-dom";
const AdminSideNavBar = () => {
const { user: currentUser } = useSelector((state) => state.auth);
const dispatch = useDispatch();
const { isLoggedIn } = useSelector((state) => state.auth);
const logOut = () => {
dispatch(logout());
};
return (
<div className="stickysidenav">
<CDBSidebar textColor="#fff" backgroundColor="#333">
<CDBSidebarHeader prefix={<i className="fa fa-bars fa-large"></i>}>
<a
href="/"
className="text-decoration-none"
style={{ color: "inherit" }}
>
TradeDuh
</a>
<p>{currentUser.username}</p>
{/* {isLoggedIn && (
<div className="wrapper">
<p>{currentUser.username}</p>
</div>
)} */}
</CDBSidebarHeader>
<CDBSidebarContent className="sidebar-content">
<CDBSidebarMenu>
<NavLink exact to="/dashboard" activeClassName="activeClicked">
<CDBSidebarMenuItem icon="columns">Dashboard</CDBSidebarMenuItem>
</NavLink>
<NavLink exact to="/logs" activeClassName="activeClicked">
<CDBSidebarMenuItem icon="table">Logs</CDBSidebarMenuItem>
</NavLink>
<NavLink exact to="/uploadcompany" activeClassName="activeClicked">
<CDBSidebarMenuItem icon="edit">Update Nasdaq Stocks</CDBSidebarMenuItem>
</NavLink>
<NavLink exact to="/manageusers" activeClassName="activeClicked">
<CDBSidebarMenuItem icon="users-cog">Manage Users</CDBSidebarMenuItem>
</NavLink>
<NavLink exact to="/activeusers" activeClassName="activeClicked">
<CDBSidebarMenuItem icon="user-check">Active Users</CDBSidebarMenuItem>
</NavLink>
<NavLink exact to="/deactivatedusers" activeClassName="activeClicked">
<CDBSidebarMenuItem icon="user-times">De-activated Users</CDBSidebarMenuItem>
</NavLink>
<NavLink to="/registerinternalusers" activeClassName="activeClicked">
<CDBSidebarMenuItem icon="user-plus">
Add Internal Users
</CDBSidebarMenuItem>
</NavLink>
<NavLink
exact
to="/login"
activeClassName="activeClicked"
onClick={logOut}
>
<CDBSidebarMenuItem icon="sign-out-alt">
Log Out
</CDBSidebarMenuItem>
</NavLink>
</CDBSidebarMenu>
</CDBSidebarContent>
<CDBSidebarFooter style={{ textAlign: "center" }}>
<div
style={{
padding: "20px 5px",
}}
>
TradeDuh (FDM - S21-Java-02)
</div>
</CDBSidebarFooter>
</CDBSidebar>
</div>
);
};
export default AdminSideNavBar;
The issue is, once I reach the various page, if I do a manual refresh (ctrl r), my whole screen will turn white/blank.
So say if I click on /logs, AdminLogs component is rendered, which is all good. BUT... if I now press ctrl r to do a manual fresh, the AdminLogs component don't show anymore. All I see is a blank white screen.
This is totally different from what is happening in my main router where I can do a manual page fresh and the page will render accordingly.
Any idea on how to solve this? What is my issue here?
Thank you for the help!

How to transition from one page to another in react app

i am trying create a transition screen from one page to the other
function MainPage(){
return (
<div>
{pagestate.navigating == "true" ? (
<FadeIn>
<div className="d-flex justify-content-center align-items-center">
<h1>signing you in ....</h1>
<Link to="/" color="black" >sign in</Link>
{pagestate.loading =="false" ? (
<Lottie options={defaultOptions} height={120} width={120} />
) : (
<Lottie options={defaultOptions2} height={220} width={120} />
)}
</div>
</FadeIn>
) : (
<div>
<h1>hello world</h1>
<Link to="/" color="black" >sign in</Link>
</div>
)}
The code works fine but I want it to navigate to /page2 when pagestate.loading = "false". I was able to achieve the page navigation with using
const history = useHistory()
then call navigation like
history.push('/page2')
I tried couple of method but could not get it work inside the transition logic.
How can I incorporate to the navigation into a new page after loading state has been changed to false in the transition logic above?
Encountered that a couple of days ago, i found a solution to it but it’s kinda weird,i’ve done it using redux, i’ve made a Link Component Called LinkWithAnimation,created a reducer as RouteReducer which will store current transition state, 2 states:
First one is For Transitioning In.
Second one is For Transitioning Out.
Wrapped my application with a div and passed the Transition that’s stored in redux, everytime LinkWithAnimation Is clicked This Is What Happens:
Dispatch An Action For Transitioning In
Wait(Delay) Till the Transition Has Finished(Depending On The Duration Of It)
Dispatch An Action for Transitioning Out.
And then push the new path using History API.
Note: Make Use Of Redux Thunk.
ActionTypes.js
export const ActionsType = {
...otherActions,
ANIMATION_IN: "animation-in",
ANIMATION_OUT: "animation-out",
};
ActionsCreator.js
import { ActionsType } from "./ActionsType.js";
import { history } from "../index.js";
export const ActionsCreator = {
...otherActionCreators,
userLogout: () => ({ type: ActionsType.LOGOUT }),
animateIn: () => ({ type: ActionsType.ANIMATION_IN }),
animateOut: () => ({ type: ActionsType.ANIMATION_OUT }),
pageTransition: (duration, path) => {
return async (dispatch) => {
const delay = async () => {
return new Promise((resolve) => setTimeout(resolve, duration));
};
dispatch(ActionsCreator.animateOut());
await delay();
dispatch(ActionsCreator.animateIn());
history.push(path);
};
},
};
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Router } from "react-router-dom";
import { createBrowserHistory } from "history";
export const history = createBrowserHistory();
ReactDOM.render(
<Router history={history}>
<React.StrictMode>
<App />
</React.StrictMode>
</Router>,
document.getElementById("root")
);
LinkWithAnimation.js
import React, { useRef, useEffect } from "react";
import { Link } from "react-router-dom";
import { ActionsCreator } from "../actions/ActionsCreator.js";
import { connect } from "react-redux";
const LinkWithAnimation = ({
className,
additionalFunction,
PageTransitioning,
to,
children,
style,
component,
ReactTo,
disabled,
}) => {
const LinkRef = useRef();
// This Effect To Handle Page Transition Once The User Is Signed In
useEffect(() => {
if (ReactTo === true) {
LinkRef.current.click();
}
}, [ReactTo]);
const componentProp =
component !== undefined
? {
component: component,
}
: {};
return (
<>
<Link
onClick={async () => {
if (disabled) return;
PageTransitioning(230, to);
if (additionalFunction !== undefined) {
additionalFunction();
}
}}
ref={LinkRef}
className={className}
style={{ ...style }}
{...componentProp}
>
{children}
</Link>
</>
);
};
const mapDispatchToProps = (dispatch) => ({
PageTransitioning: (duration, path) => {
dispatch(ActionsCreator.pageTransition(duration, path));
},
});
export default connect(null, mapDispatchToProps)(LinkWithAnimation);
Main.js
import React, { Fragment } from "react";
import { Switch, Route } from "react-router-dom";
import { connect } from "react-redux";
import Homepage from "./Homepage/Homepage.js";
import Signup from "./Signup/Signup.js";
import UserInterface from "./UserInterface/UserInterface.js";
import { SignIn } from "./SignIn/SignIn.js";
import { useRouteTransitionScroll } from "../hooks/useRouteTransitionScroll.js";
const Main = ({ keyframe }) => {
useRouteTransitionScroll({
from: "/signup",
to: "/home",
scroll_y: 650,
});
return (
<Switch component={Fragment}>
<div
style={{
animationName: keyframe,
animationDuration: "250ms",
animationTimingFunction: "linear",
}}
>
<Route path="/mainpage">
<UserInterface />
</Route>
<Route path="/home">
<Homepage />
</Route>
<Route path="/signin">
<SignIn />
</Route>
<Route path="/signup">
<Signup />
</Route>
</div>
</Switch>
);
};
const mapStateToProps = (state) => ({
keyframe: state.Route.animationName,
});
export default connect(mapStateToProps)(Main);

Categories