page needs refresh when click on a route [duplicate] - javascript

This question already has answers here:
Link tag inside BrowserRouter changes only the URL, but doesn't render the component
(2 answers)
Closed 9 months ago.
My problem is that when I click on an element defined by Route, the URL changes but the page does not change and I have to reload the page once to change the page.
i have no idea what is happening here
Node.js: 16.5
npm: 8.10.0
react-router-dom: 5.3.1
Thanks for your help
Routes:
import React from "react";
import { Route, Switch, BrowserRouter } from "react-router-dom";
import Login from "../Login/login";
import Navbar from "../Navbar/navbar";
export default function Routers(){
return(
<BrowserRouter>
<Switch>
<Route path="/log-in">
<Login />
</Route>
<Route path="/">
<Navbar />
</Route>
</Switch>
</BrowserRouter>
);
}
navbar.js:
import React from "react";
import * as Mu from "#mui/material";
import { Link } from "react-router-dom";
export default function Navbar(){
return(
<Link to="/log-in">
<Mu.Button variant="contained" color="success">Log in</Mu.Button>
</Link>
)
}
App.js:
import React from "react";
import Routers from "./commponents/Routes/routes";
function App() {
return (
<div className="App">
<Routers />
</div>
);
}
export default App;
login.js:
import React from "react";
import * as Mu from "#mui/material";
import * as Icons from "#mui/icons-material";
import study from "../.././assets/img/study.jpg"
import uni from "../.././assets/img/Uni-3.png";
import homework from "../.././assets/img/homework.jpg";
export default function Login(){
return (
<Mu.Grid container className="h-100 justify-content-center">
<Mu.Grid item sm={12} className="text-center login">
<Mu.Box className="login-box d-inline-block">
<Mu.Grid container dir="rtl" className="h-100">
<Mu.Grid item xs={12} md={7} className="login">
<div className="w-100">
<Mu.Card sx={{ maxWidth: "100%" }} className="d-md-none d-sm-block d-block login-card">
<Mu.CardMedia component="img" alt="green iguana" width="100%" height="100" className="login-card" image={homework}/>
</Mu.Card>
<Mu.Container fixed>
<Mu.Avatar alt="profile" className="text-center bg-white border d-inline-block ms-3 mb-3 prof-pic" src={uni} sx={{ width: 70, height: 70 }}/>
<h4 className="ps-md-4 ps-sm-0 ps-0">ورود به پنل مدیران</h4>
<Mu.Box sx={{ display: 'flex', width:"100%", alignItems: 'flex-end' }} className="px-md-3 px-sm-0 px-0">
<Icons.Person sx={{ color: 'action.active', mr: 1, ml: 3 }} />
<Mu.TextField id="username" label="نام کاربری" className="w-75" variant="standard" />
</Mu.Box>
<Mu.Box sx={{ display: 'flex', width:"100%", alignItems: 'flex-end', mt: 1 }} className="px-md-3 px-sm-0 px-0">
<Icons.Lock sx={{ color: 'action.active', mr: 1, ml: 3 }} />
<Mu.TextField id="password" label="رمز عبور" className="w-75" variant="standard" />
</Mu.Box>
<Mu.Button sx={{ mt: 4, width: "50%"}} variant="contained">ورود</Mu.Button>
</Mu.Container>
</div>
</Mu.Grid>
<Mu.Grid item xs={12} md={5} className="h-100 d-md-block d-sm-none d-none">
<img src={study} width="100%" height="100%" className="login-img" />
</Mu.Grid>
</Mu.Grid>
</Mu.Box>
</Mu.Grid>
</Mu.Grid>
);
}

Add exact attribute to your index route <Route exact path="/">.
If it does not work try wrapping components with withRouter: <Route exact path="/" component={withRouter(Component)}
Also move <BrowserRouter> to your main file, example:
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);

Related

react-router-dom doesn't redirect to the linked page, instead it shows the content of the linked page below the menu

I'm currently trying to get my footer navmenu to work. It seemed like react-router-dom was the best choice for that, but I can't get it to redirect to the linked page. Instead the content of the Linked page shows up below the menu.
<Router>
<div
style={{
textAlign: "center",
alignItems: "center",
alignContent: "center"
}}
>
<a style={{ marginRight: "10px", fontSize: "20px" }}>
Impressum
</a>
<a style={{ marginRight: "10px", fontSize: "20px" }}>
<Link to="/Datenschutz">Datenschutz</Link>
</a>
<a style={{ marginRight: "10px", fontSize: "20px" }}>
Kontakt
</a>
</div>
<Routes>
<Route
path="/Datenschutz"
element={<Datenschutz />}
/>
</Routes>
</Router>
I recreated the issue in codesandbox:
https://codesandbox.io/s/headless-shape-rghsi7?file=/src/footer.js
You are rendering the router and route in the Footer component.
Move the Router and routes from Footer into the App component. By promoting the Router higher in the ReactTree the routing context it provides is available to all the components under it. The links in the Footer will allow navigation to routes rendered in App.
Example:
import {
BrowserRouter as Router,
Routes,
Route,
} from "react-router-dom";
import Footer1 from "./footer";
import Datenschutz from "./Datenschutz";
import "./styles.css";
export default function App() {
return (
<Router>
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Routes>
<Route path="/Datenschutz" element={<Datenschutz />} />
</Routes>
<Footer1 />
</div>
</Router>
);
}

How do I fix a <Link> component error issue in React app?

I'm experiencing an issue with the <Link> component from react-router-dom.
The above error occurred in the <Link> component:
at LinkWithRef (http://localhost:3000/react-portfolio/static/js/bundle.js:64573:7)
at button
at http://localhost:3000/react-portfolio/static/js/bundle.js:3642:66
at ButtonBase (http://localhost:3000/react-portfolio/static/js/bundle.js:9678:82)
at http://localhost:3000/react-portfolio/static/js/bundle.js:3642:66
at Button (http://localhost:3000/react-portfolio/static/js/bundle.js:9381:59)
at div
at div
at http://localhost:3000/react-portfolio/static/js/bundle.js:3642:66
at Toolbar (http://localhost:3000/react-portfolio/static/js/bundle.js:20646:82)
at header
at http://localhost:3000/react-portfolio/static/js/bundle.js:3642:66
at Paper (http://localhost:3000/react-portfolio/static/js/bundle.js:18055:82)
at http://localhost:3000/react-portfolio/static/js/bundle.js:3642:66
at AppBar (http://localhost:3000/react-portfolio/static/js/bundle.js:8771:83)
at div
at http://localhost:3000/react-portfolio/static/js/bundle.js:3642:66
at Box (http://localhost:3000/react-portfolio/static/js/bundle.js:23577:72)
at div
at Navbar (http://localhost:3000/react-portfolio/static/js/bundle.js:629:5)
at div
at PortfolioContainer (http://localhost:3000/react-portfolio/static/js/bundle.js:1060:88)
at div
at App
at Router (http://localhost:3000/react-portfolio/static/js/bundle.js:66149:15)
at BrowserRouter (http://localhost:3000/react-portfolio/static/js/bundle.js:64481:5)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError # react-dom.development.js:18687
I'm guessing that this is located in my Navbar file somewhere, which you can see below:
import * as React from 'react';
import AppBar from '#mui/material/AppBar';
import Box from '#mui/material/Box';
import Toolbar from '#mui/material/Toolbar';
import Typography from '#mui/material/Typography';
import Button from '#mui/material/Button';
import { Link } from 'react-router-dom';
import IconButton from '#mui/material/IconButton';
import Menu from '#mui/material/Menu';
import MenuIcon from '#mui/icons-material/Menu';
import MenuItem from '#mui/material/MenuItem';
import '../styles/root.css';
import useWindowDimension from '../utils/windowDimensions';
import About from '../pages/About';
import Contact from '../pages/Contact';
import Portfolio from '../pages/Portfolio';
import Resume from '../pages/Resume';
export default function Navbar({ handlePageChange }) {
const { height, width } = useWindowDimension();
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const [anchorElNav, setAnchorElNav] = React.useState(null);
const openNav = Boolean(anchorElNav);
const handleOpenNavMenu = (event) => {
setAnchorElNav(event.currentTarget);
};
const handleCloseNavMenu = () => {
setAnchorElNav(null);
}
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<Box sx={{ flexGrow: 1, width: "100%" }} >
<AppBar position="static" id="navbar">
<Toolbar>
<Typography
id="nav-logo"
variant="h6"
component="div"
sx={{ flexGrow: 1 }}
fontFamily="reklame-script, sans-serif"
fontWeight="700"
fontStyle="normal"
fontSize="36px"
// onClick={() => handlePageChange('About')}
>
My Portfolio
</Typography>
{width >= 900
?
<div
style={{ display: "flex", direction: "row", flexWrap: "wrap", justifyContent: "space-evenly", alignContent: "center", fontWeight: "bold" }}
>
<Button
color="inherit"
onClose={handleClose}
// onClick={() => handlePageChange('About')}
>
<Link to={<About />}>
About Me
</Link>
</Button>
<Button
color="inherit"
onClose={handleClose}
// onClick={() => handlePageChange('Portfolio')}
>
<Link to={<Portfolio />}>
Portfolio
</Link>
</Button>
<Button
color="inherit"
onClose={handleClose}
// onClick={() => handlePageChange('Contact')}
>
<Link to={<Contact />}>
Contact Me
</Link>
</Button>
<Button
color="inherit"
onClose={handleClose}
// onClick={() => handlePageChange('Contact')}
>
<Link to={<Resume />}>
Resume
</Link>
</Button>
</div>
:
// Mobile Hamburger Menu
<Box id='hamburger-menu' sx={{ flexGrow: 1, display: { xs: "flex", md: "none" }, justifyContent: "right" }}>
<IconButton
id="menu-button"
size="large"
aria-controls={openNav ? 'menu-appbar' : undefined}
aria-haspopup="true"
aria-expanded={openNav ? 'true' : undefined}
onClick={handleOpenNavMenu}
color="inherit"
>
<MenuIcon />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorElNav}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={openNav}
onClose={handleCloseNavMenu}
sx={{
display: { xs: 'block', md: 'none' },
}}
>
<div>
<MenuItem className='mobileMenuItem' onClick={handleCloseNavMenu}>
<Button color="inherit" >
<Link style={{ textDecoration: "none", color: "black" }} to="/" onClose={handleClose}>
About Me
</Link>
</Button>
</MenuItem>
<MenuItem className='mobileMenuItem' onClick={handleCloseNavMenu}>
<Button color="inherit" onClose={handleClose}>
<Link style={{ textDecoration: "none", color: "black" }} to={"/portfolio"}>
Portfolio
</Link>
</Button>
</MenuItem>
<MenuItem className='mobileMenuItem' onClick={handleCloseNavMenu}>
<Button color="inherit" onClose={handleClose}>
<Link style={{ textDecoration: "none", color: "black" }} to="/contact">
Contact Me
</Link>
</Button>
</MenuItem>
<MenuItem className='mobileMenuItem' onClick={handleCloseNavMenu}>
<Button color="inherit" onClose={handleClose}>
<Link style={{ textDecoration: "none", color: "black" }} to="/resume">
Resume
</Link>
</Button>
</MenuItem>
<Menu
id="basic-menu"
anchorEl={anchorEl}
open={open}
MenuListProps={{
'aria-labelledby': 'basic-button',
}}
onClick={handleClick}
onClose={handleClose}
>
</Menu>
</div>
</Menu>
</Box>
}
</Toolbar>
</AppBar>
</Box>
</div>
);
}
If it's not there, perhaps it's in my PortfolioContainer file? This can be seen below.
import React, { useState } from "react";
import About from "../pages/About";
import Portfolio from "../pages/Portfolio";
import Contact from "../pages/Contact";
import Resume from "../pages/Resume";
import Navbar from "../components/Navbar";
import Footer from "../components/Footer";
export default function PortfolioContainer() {
const [currentPage, setCurrentPage] = useState('');
const renderPage = () => {
if (currentPage === '/') {
return <About />
}
if (currentPage === '/resume') {
return <Resume />;
}
if (currentPage === '/portfolio') {
return <Portfolio />;
}
if (currentPage === '/contact') {
return <Contact />;
}
// return <About />;
};
const handlePageChange = (page) => setCurrentPage(page);
return (
<div id="portfolioContainer">
<Navbar currentPage={currentPage} handlePageChange={handlePageChange} />
{renderPage()}
<Footer />
</div>
);
};
Thank you in advance for any and all help!
I assumed you are useing react-router-dom#6.6.1 (latest version). "to" prop from component expect a string but you provide the component. That's why you get cyclic object error. I took your code an defined a router in index.js file like this
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import App from "./App";
import Resume from "./Resume";
const router = createBrowserRouter([
{
path: "/",
element: <App />
},
{
path: "/resume",
element: <Resume />
}
]);
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<RouterProvider router={router} />
</StrictMode>
);
and in my App.js file I used Link component like this
<Button
color="inherit"
onClose={handleClose}
>
<Link to="/resume">Resume</Link>
</Button>
The issue it seems is that you aren't using react-router to its fullest. The Link component should be specifying a to prop that matches a URL pathname that you are rendering a Route component for. PortfolioContainer should be rendering the routes you are trying to link to from the Navbar component.
Example:
PortfolioContainer
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import About from "../pages/About";
import Portfolio from "../pages/Portfolio";
import Contact from "../pages/Contact";
import Resume from "../pages/Resume";
import Navbar from "../components/Navbar";
import Footer from "../components/Footer";
export default function PortfolioContainer() {
return (
<BrowserRouter>
<div id="portfolioContainer">
<Navbar />
<Routes>
<Route path="/" element={<About />} />
<Route path="/resume" element={<Resume />} />
<Route path="/portfolio" element={<Portfolio />} />
<Route path="/contact" element={<Contact />} />
</Routes>
<Footer />
</div>
</BrowserRouter>
);
};
Navbar
...
<Link to="/">
About Me
</Link>
...
<Link to="/portfolio">
Portfolio
</Link>
...

Material ui library margin bottom problem

Hi Everyone, Many Greetings from Turkey.
firstly this is my App.js Codes
/* React Imports*/
import { Routes, Route } from "react-router-dom";
import { useState } from "react";
/*Local Imports */
import { ColorModeContext, useMode } from "./theme";
import Dashboard from "./WorkPages/Dashboard/Dashboard";
import Topbar from "./WorkPages/GlobalPages/Topbar";
import Sidebar from "./WorkPages/GlobalPages/Sidebar";
import Team from "./WorkPages/Team/Team";
import CreateNewUser from "./WorkPages/CreateNewUser/CreateNewUser";
import Projects from "./WorkPages/Projects/Projects";
import CreateNewProjects from "./WorkPages/CreateNewProject/CreateNewProject";
import Bar from "./WorkPages/BarChart/BarChart";
import PieChart from "./WorkPages/PieChart/PieChart";
import LineChartGraph from "./WorkPages/LineChartGraph/LineChartGraph";
import TeamLocation from "./WorkPages/TeamLocation/TeamLocation";
import ProductBooks from "./WorkPages/ProductBooks/ProductBooks";
import WorkPlan from "./WorkPages/WorkPlan/WorkPlan";
import RoomInfoInput from "./WorkPages/RoomInfoInput/RoomInfoInput";
import StairsInfoInput from "./WorkPages/StairsInfoInput/StairsInfoInput";
import Specifications from "./WorkPages/Specifications/Specifications";
import InteractiveDB from "./WorkPages/InteractiveDB/InteractiveDB";
import Multiplication from "./WorkPages/Multiplication/Multiplication";
import ImportData from "./WorkPages/ImportData/ImportData";
import ExportData from "./WorkPages/ExportData/ExportData";
import HelpMenu from "./WorkPages/HelpMenu/HelpMenu";
/*MUI Imports */
import { CssBaseline, ThemeProvider } from "#mui/material";
import BarChart from "./components/_BarChart";
import Tabs from "#mui/material/Tabs";
function App() {
const [theme, colorMode] = useMode();
const [isSidebar, setIsSidebar] = useState(true);
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<CssBaseline />
<Tabs>
<div className="app">
<Sidebar isSidebar={isSidebar} />
<main className="content">
<Topbar setIsSidebar={setIsSidebar} />
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/team" element={<Team />} />
<Route
path="/createnewuser"
element={<CreateNewUser />}
/>
<Route path="/projects" element={<Projects />} />
<Route
path="/createnewproject"
element={<CreateNewProjects />}
/>
<Route path="/barchart" element={<BarChart />} />
<Route path="/piechart" element={<PieChart />} />
<Route path="/linechart" element={<LineChartGraph />} />
<Route
path="/teamlocation"
element={<TeamLocation />}
/>
<Route
path="/productbooks"
element={<ProductBooks />}
/>
<Route path="/workplan" element={<WorkPlan />} />
<Route
path="/roominfoinput"
element={<RoomInfoInput />}
/>
<Route
path="/stairsinfoinput"
element={<StairsInfoInput />}
/>
<Route
path="/specifications"
element={<Specifications />}
/>
<Route
path="/interactivedb"
element={<InteractiveDB />}
/>
<Route
path="/multiplication"
element={<Multiplication />}
/>
<Route path="/importdata" element={<ImportData />} />
<Route path="/exportdata" element={<ExportData />} />
<Route path="/helpmenu" element={<HelpMenu />} />
</Routes>
</main>
</div>
</Tabs>
</ThemeProvider>
</ColorModeContext.Provider>
);
}
export default App;
My index.css codes
/* Google Fonts */
#import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght#400;600;700&display=swap');
/* CSS CODES*/
html,
body,
#root,
.app,
.content {
height: 100%;
width: 100%;
font-family: "Source Sans Pro", sans-serif;
overflow: hidden;
/* Default Font Will be "Source Sans Pro" */
}
.app {
display: flex;
position: relative;
}
/* Scroll Bar Setting */
::-webkit-scrollbar {
width: 10px;
}
/* Track Bar Setting */
::-webkit-scrollbar-track {
background: #e0e0e0;
}
/* Handle Setting */
::-webkit-scrollbar-thumb {
background: #888;
}
/* Handle On Hover Setting */
::-webkit-scrollbar-track:hover {
background: #555;
}
and current view of my project on the browser
How can I fix this problem with css codes or without css so with MUI classes? I tried many way to fix that but I didn't get a solution.
I tried
overflow:hidden
code lines but they're doesn't working for my problem.
here is my sidebar codes
/*REACT IMPORTS*/
import { useState } from "react";
import { Link } from "react-router-dom";
/*MUI IMPORTS*/
import { Box, IconButton, Typography, useTheme } from "#mui/material";
/*MUI ICONS IMPORTS*/
import MenuOutlinedIcon from "#mui/icons-material/MenuOutlined";
import HomeOutlinedIcon from "#mui/icons-material/HomeOutlined";
import EngineeringOutlinedIcon from "#mui/icons-material/EngineeringOutlined";
import FoundationOutlinedIcon from "#mui/icons-material/FoundationOutlined";
import BarChartOutlinedIcon from "#mui/icons-material/BarChartOutlined";
import DonutSmallOutlinedIcon from "#mui/icons-material/DonutSmallOutlined";
import StackedLineChartOutlinedIcon from "#mui/icons-material/StackedLineChartOutlined";
import LocationSearchingOutlinedIcon from "#mui/icons-material/LocationSearchingOutlined";
import MenuBookOutlinedIcon from "#mui/icons-material/MenuBookOutlined";
import CalendarMonthOutlinedIcon from "#mui/icons-material/CalendarMonthOutlined";
import InputOutlinedIcon from "#mui/icons-material/InputOutlined";
import StairsOutlinedIcon from "#mui/icons-material/StairsOutlined";
import LibraryBooksOutlinedIcon from "#mui/icons-material/LibraryBooksOutlined";
import StorageOutlinedIcon from "#mui/icons-material/StorageOutlined";
import DynamicFeedOutlinedIcon from "#mui/icons-material/DynamicFeedOutlined";
import FileUploadOutlinedIcon from "#mui/icons-material/FileUploadOutlined";
import FileDownloadOutlinedIcon from "#mui/icons-material/FileDownloadOutlined";
import HelpOutlinedIcon from "#mui/icons-material/HelpOutlined";
/*LOCAL IMPORTS*/
import { tokens } from "../../theme";
/*OTHER IMPORTS MAIN COMMENT*/
/*REACT PRO SIDEBAR IMPORTS*/
import { ProSidebar, Menu, MenuItem } from "react-pro-sidebar";
import "react-pro-sidebar/dist/css/styles.css";
/*-----------Components--------------*/
const Item = ({ title, to, icon, selected, setSelected }) => {
const theme = useTheme();
const colors = tokens(theme.palette.mode);
return (
<MenuItem
active={selected == title}
style={{ color: colors.grey[100] }}
onClick={() => setSelected(title)}
icon={icon}>
<Typography>{title}</Typography>
<Link to={to} />
</MenuItem>
);
};
const Sidebar = () => {
const theme = useTheme();
const colors = tokens(theme.palette.mode);
const [isCollapsed, setIsCollapsed] = useState(false);
const [selected, setSelected] = useState("Dashboard");
return (
<Box
sx={{
"& .pro-siderbar-inner": {
background: `${colors.primary[400]} !important`,
},
"& .pro-icon-wrapper": {
backgroundColor: "transparent ! important",
},
"& .pro-inner-item": {
padding: "5px 35px 5px 20px !important",
},
"& .pro-inner-item:hover": {
color: "#F08221 !important",
},
"& .pro-menu-item.active": {
colors: "#6870fa !important",
},
}}>
<ProSidebar collapsed={isCollapsed}>
{/* COMPANY LOGO AND MENU ICON */}
<Menu iconShape='square'>
<MenuItem
onClick={() => setIsCollapsed(!isCollapsed)}
icon={
isCollapsed ? (
<MenuOutlinedIcon fontSize='large' />
) : undefined
}
style={{ margin: "10px 0 20px 0", color: colors.grey[100] }}>
{!isCollapsed && (
<Box
display='flex'
justifyContent='space-between'
alignItems='center'
ml='15px'
overflow='hidden'>
<Typography variant='h3'>Metraj Merkezi</Typography>
<IconButton
onClick={() => setIsCollapsed(!isCollapsed)}>
<MenuOutlinedIcon fontSize='large' />
</IconButton>
</Box>
)}
</MenuItem>
{!isCollapsed && (
<Box mb='25px'>
<Box
display='flex'
justifyContent='center'
alignItems='center'>
<img
alt='profile-user'
width='100px'
height='100px'
src={`../../assets/fikret.jpg`}
style={{ cursor: "pointer", borderRadius: "50%" }}
/>
</Box>
<Box textAlign='center'>
<Typography variant='h3' color={colors.grey[100]}>
Fikret AKBAŞ
</Typography>
<Typography variant='h6' color={colors.grey[500]}>
Metraj Merkezi CEO
</Typography>
</Box>
</Box>
)}
<Box paddingLeft={isCollapsed ? undefined : "10%"}>
<Item
title='Anasayfa'
to='/'
icon={<HomeOutlinedIcon fontSize='large' />}
selected={selected}
setSelected={setSelected}
/>
<Typography
variant='h6'
color={colors.grey[300]}
sx={{ m: "15px 0 5px 20px" }}>
Yönetici Paneli
</Typography>
<Item
title='Takımı Yönet'
to='/team'
icon={<EngineeringOutlinedIcon fontSize='large' />}
selected={selected}
setSelected={setSelected}
/>
... there are many items but I didn't add here for too long waste codes here
</Box>
</Menu>
</ProSidebar>
</Box>
);
};
export default Sidebar;
here is my Topbar codes
/*REACT IMPORTS*/
import { useContext } from "react";
/*MUI IMPORTS*/
import { Box, IconButton, useTheme } from "#mui/material";
import InputBase from "#mui/material/InputBase";
/*MUI ICONS IMPORTS*/
import LightModeOutlinedIcon from "#mui/icons-material/LightModeOutlined";
import DarkModeOutlinedIcon from "#mui/icons-material/DarkModeOutlined";
import NotificationsOutlinedIcon from "#mui/icons-material/NotificationsOutlined";
import SettingsOutlinedIcon from "#mui/icons-material/SettingsOutlined";
import PersonOutlinedIcon from "#mui/icons-material/PersonOutlined";
import SearchIcon from "#mui/icons-material/Search";
import FolderSharedOutlinedIcon from "#mui/icons-material/FolderSharedOutlined";
import FactCheckOutlinedIcon from "#mui/icons-material/FactCheckOutlined";
/*LOCAL IMPORTS*/
import { ColorModeContext, tokens } from "../../theme";
/*OTHER IMPORTS MAIN COMMENT*/
/*OTHER IMPORTS*/
/*-----------Components--------------*/
const Topbar = () => {
const theme = useTheme();
const colors = tokens(theme.palette.mode);
const colorMode = useContext(ColorModeContext);
return (
<Box display="flex" justifyContent="space-between" p={2}>
{/* SEARCH BAR */}
<Box
display="flex"
backgroundColor={colors.primary[700]}
borderRadius="3px"
>
<InputBase sx={{ ml: 2, flex: 1 }} placeholder="Search" />
<IconButton type="button" sx={{ p: 1 }}>
<SearchIcon />
</IconButton>
</Box>
{/* ICONS */}
<Box display="flex" border="1px solid" borderRadius={3}>
<IconButton onClick={colorMode.toggleColorMode}>
{theme.palette.mode === "dark" ? (
<LightModeOutlinedIcon />
) : (
<DarkModeOutlinedIcon />
)}
</IconButton>
<IconButton>
<FactCheckOutlinedIcon />
</IconButton>
<IconButton>
<FolderSharedOutlinedIcon />
</IconButton>
<IconButton>
<NotificationsOutlinedIcon />
</IconButton>
<IconButton>
<SettingsOutlinedIcon />
</IconButton>
<IconButton>
<PersonOutlinedIcon />
</IconButton>
</Box>
</Box>
);
};
export default Topbar;

React Router Dom not rendering components but changes URL

I was pushing code into github when somehow my react router code stopped working. The components are not rendering yet the url is changing. Even when I replace with a basic html tag, nothing renders. I am really lost and could use some help.
Dashboard.jsx
import React from "react";
import Home from './Home/homeDashboard.jsx'
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Map from '#material-ui/icons/MapOutlined';
import Test from './MyPlan/Modules.jsx';
function Dashboard() {
const routes = [
{
path: "/home",
main: () => <Home />
},
{
path: "/myplan",
main: () => <Test />,
},
];
return (
<div style={{ backgroundColor: '#F5F5F5', height: '100vh' }}>
<Router>
<div style={{ display: 'flex' }}>
<nav className={classes.nav}>
<IconButton className={classes.navBtn} component={Link} to="/home" style={{ color: "rgb(255,255,255)" }} >
<Tooltip title="Home" className={classes.toolTip}>
<HomeIcon />
</Tooltip>
</IconButton>
<IconButton className={classes.navBtn} component={Link} to="/myplan" style={{ color: "rgb(255,255,255)" }}>
<Tooltip className={classes.toolTip} title="My Plan" >
<Map />
</Tooltip>
</IconButton>
</nav>
<div style={{ flex: 1 }}>
<Switch>
{routes.map((route, index) => (
<Route
key={index}
path={route.path}
children={<route.main />}
/>
))}
</Switch>
</div>
</div>
</Router>
</div>
);
}
export default Dashboard;

Content disappears after routing from login page? React Router Dom + Electron

Summary
I'm building an electron app with react. Currently I have 2 main routes - a login page, and a dashboard. The dashboard has 3 sub routes controlled by a sidebar. The 3 sub routes - home, install, and settings - are displayed in a main content area alongside the sidebar. This approach works fine by itself. The issue arises when I string in the login page. I've been successful in routing from the login to the main page area, but the sub routes fail to render when I do so.
The problem
When I route from login, to the dashboard, my layout appears fine. Once i click on an option in the sidebar, the DOM goes blank. I've moving around my routes and divs, but haven't had much luck this way. Here is the code for my setup. Sometimes, I can even see a flash of the main content that should be there before it blanks.
Another thing I've tried is changing my entry point router to include a <Switch> above the 2 routes. With that setup, I could get from login, to dashboard, but clicking a sidebar option would send me back to login.
index.js - entry point
const routing = (
<HashRouter>
<Route exact path="" component={Auth}/>
<Route exact path="/dashboard" component={Layout} />
</HashRouter>
)
ReactDOM.render(routing, document.getElementById('root'));
When the input from auth is correct, I run this:
if(this.state.loginResult){
return(
<Redirect to={'/dashboard'} />
)
Layout.js - the dashbaord.
render() {
return (
<HashRouter>
<div>
<Installer onRef={ref => (this.child = ref)} />
<div className={'sideBar'}>
<div className={'navSelect'}>
<NavLink to={'/home'} activeClassName="navOptionActive" >
<div className={'navOption'} >
<HomeIcon
style={{fontSize: 75, textAlign: 'center', alignSelf: 'center',
color: 'white', marginTop: 10, marginBottom: 0}}/>
<h1>Home</h1>
</div>
</NavLink>
<NavLink to={'/test'} activeClassName="navOptionActive">
<div className={'navOption'}>
<Brightness3Icon
style={{fontSize: 75, textAlign: 'center', alignSelf: 'center',
color: 'white', marginTop: 10, marginBottom: 0}}/>
<h1>Nightly</h1>
</div>
</NavLink>
<div className={'bottom'}>
<NavLink to={'/nothing'} exact activeClassName="navOptionActive">
<div className={'navOption'} id={'settings'}>
<SettingsIcon
style={{fontSize: 75, textAlign: 'center', alignSelf: 'center',
color: 'white', marginTop: 10, marginBottom: 0}}/>
<h1>Settings</h1>
</div>
</NavLink>
</div>
</div>
</div>
{/*Main content area. This is where the content from the sidebar options will be displayed. */}
<div className={'mainContent'} >
<Route path="/home">
<App />
</Route>
<Route path="/test">
<TestPage install={this.install} />
</Route>
</div>
</div>
</HashRouter>
Also note, I don't have a settings page linked up yet which is why one of the navlinks goes to /nothing.
Remove the nested hashRouting from the Layout component and add Switch to the top component.
index.js - entry point
const routing = (
<HashRouter>
<Switch>
<Route exact path="" component={Auth}/>
<Route exact path="/dashboard" component={Layout} />
</Switch>
</HashRouter>
)
ReactDOM.render(routing, document.getElementById('root'));
Layout.js - the dashbaord.
render() {
return (
<div>
<Installer onRef={ref => (this.child = ref)} />
<div className={'sideBar'}>
<div className={'navSelect'}>
<NavLink to={'/home'} activeClassName="navOptionActive" >
<div className={'navOption'} >
<HomeIcon
style={{fontSize: 75, textAlign: 'center', alignSelf: 'center',
color: 'white', marginTop: 10, marginBottom: 0}}/>
<h1>Home</h1>
</div>
</NavLink>
<NavLink to={'/test'} activeClassName="navOptionActive">
<div className={'navOption'}>
<Brightness3Icon
style={{fontSize: 75, textAlign: 'center', alignSelf: 'center',
color: 'white', marginTop: 10, marginBottom: 0}}/>
<h1>Nightly</h1>
</div>
</NavLink>
<div className={'bottom'}>
<NavLink to={'/nothing'} exact activeClassName="navOptionActive">
<div className={'navOption'} id={'settings'}>
<SettingsIcon
style={{fontSize: 75, textAlign: 'center', alignSelf: 'center',
color: 'white', marginTop: 10, marginBottom: 0}}/>
<h1>Settings</h1>
</div>
</NavLink>
</div>
</div>
</div>
{/*Main content area. This is where the content from the sidebar options will be displayed. */}
<div className={'mainContent'} >
<Switch>
<Route path="/home">
<App />
</Route>
<Route path="/test">
<TestPage install={this.install} />
</Route>
</Switch>
</div>
</div>
Login Alternative
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
// core components
import Admin from "layouts/Admin.js";
import SignIn from "layouts/SignIn";
const hist = createBrowserHistory();
const loggedRoutes = () => (
<Switch>
<Route path="/" component={SignIn} />
<Route path="/admin" component={Admin} />
<Redirect from="/admin" to="/admin/aboutUs/whatWeDo" />
</Switch>
);
const routes = () => (
<Switch>
<Route path="/" component={SignIn} />
<Route path="/login" component={Admin} />
<Redirect from="/" to="/login" />
</Switch>
);
ReactDOM.render(
<Router history={hist}>
{checkIfAuth? loggedRoutes():routes()}
</Router>,
document.getElementById("root")
);
Hope it helps

Categories

Resources