Lazy loaded React router routes loading anyway - reactjs

I've been trying to lazy load routes in React using React.lazy and Suspense. But some components are loading regardless of the current route, exactly: Feed, Profile and Settings.
Notice I don't actually want to lazy load Components like MenuAppBar and SnackAlert but if I import them normally and remove their Suspense, code-splitting straight doesn't even work and everything loads and the whole app is just a single chunk.
import {createMuiTheme, MuiThemeProvider} from "#material-ui/core";
import {yellow} from "#material-ui/core/colors";
import CssBaseline from "#material-ui/core/CssBaseline";
import axios from "axios";
import React, {lazy, Suspense, useEffect, useState} from "react";
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import "./css/feed.css";
import "./css/style.css";
const Feed = lazy(() => import("./routes/Feed"));
const Profile = lazy(() => import("./routes/Profile"));
const Home = lazy(() => import("./routes/Home"));
const Settings = lazy(() => import("./routes/Settings"));
const NotFound = lazy(() => import("./routes/NotFound"));
const MenuAppBar = lazy(() => import("./components/MenuAppBar"));
const SnackAlert = lazy(() => import("./components/SnackAlert"));
const App: React.FC = () => {
const [isLogged, setIsLogged] = useState(localStorage.getItem("token") ? true : false);
const [user, setUser] = useState<User>(
isLogged ? JSON.parse(localStorage.getItem("userInfo") as string) : {admin: false}
);
const [openError, setOpenError] = useState<boolean>(false);
const [errorMsg, setErrorMsg] = useState<string>("");
const [severity, setSeverity] = useState<Severity>(undefined);
const [pwa, setPwa] = useState<any>(null);
const [showBtn, setShowBtn] = useState<boolean>(false);
const [isLight, setIsLight] = useState<boolean>(
(JSON.parse(localStorage.getItem("theme") as string) as boolean) ? true : false
);
const theme: customTheme = {
darkTheme: {
palette: {
type: "dark",
primary: {
main: yellow[600]
}
}
},
lightTheme: {
palette: {
type: "light",
primary: {
main: yellow[700]
}
}
}
};
window.addEventListener("beforeinstallprompt", (event) => {
event.preventDefault();
setPwa(event);
setShowBtn(true);
});
window.addEventListener("appinstalled", (e) => {
setShowBtn(false);
setErrorMsg("App installed!");
setSeverity("success");
setOpenError(true);
});
const handleClick = () => {
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
setErrorMsg(`Please, open the share menu and select "Add to Home Screen"`);
setSeverity("info");
setOpenError(true);
} else {
if (pwa) {
pwa.prompt();
pwa.userChoice.then((choiceResult: {outcome: "accepted" | "refused"}) => {
if (choiceResult.outcome === "accepted") {
setErrorMsg("App downloading in the background..");
setSeverity("info");
setOpenError(true);
}
setPwa(null);
});
}
}
};
useEffect(() => {
const token: string | null = localStorage.getItem("token");
let userInfo: User = JSON.parse(localStorage.getItem("userInfo") as string);
if (userInfo && token && !userInfo.admin) {
setUser(userInfo);
setIsLogged(true);
}
if (isLogged) {
axios
.get("/api/auth/user", {
headers: {
"x-auth-token": `${token}`
}
})
.then((res) => {
if (!userInfo || !token) {
setUser(res.data as User);
}
localStorage.setItem(`userInfo`, JSON.stringify(res.data as User));
setIsLogged(true);
})
.catch((err) => {
if (err) {
setIsLogged(false);
}
});
} else {
localStorage.removeItem("token");
localStorage.removeItem("userInfo");
}
}, [isLogged]);
return (
<MuiThemeProvider theme={isLight ? createMuiTheme(theme.lightTheme) : createMuiTheme(theme.darkTheme)}>
<CssBaseline />
<Router>
<Suspense fallback={<div></div>}>
<Route
path="/"
render={() => (
<>
<MenuAppBar
isLogged={isLogged}
setIsLogged={setIsLogged}
user={user}
setUser={setUser}
isLight={isLight}
setIsLight={setIsLight}
/>
<SnackAlert severity={severity} errorMsg={errorMsg} setOpenError={setOpenError} openError={openError} />
</>
)}
/>
</Suspense>
<Suspense fallback={<div></div>}>
<Switch>
<Route exact path="/" render={() => <Home />} />
<Route exact path="/profile/:id" render={() => <Profile />} />
<Route exact path="/feed" render={() => <Feed isLogged={isLogged} user={user} />} />
<Route
exact
path="/settings"
render={() => (
<Settings isLight={isLight} setIsLight={setIsLight} handleClick={handleClick} showBtn={showBtn} />
)}
/>
<Route render={() => <NotFound />} />
</Switch>
</Suspense>
</Router>
</MuiThemeProvider>
);
};
export default App;

You are wrapping your entire Switch in a single Suspense, so all components will be lazily loaded at the same time. You probably only want each to be fetched/loaded when the specific route is rendered the first time.
<Switch>
<Route
exact
path="/"
render={props => (
<Suspense fallback={<div>Loading...<div>}>
<Home {...props} />
</Suspense>
)}
/>
<Route
exact
path="/profile/:id"
render={props => (
<Suspense fallback={<div>Loading...<div>}>
<Profile {...props} />
</Suspense>
)}
/>
<Route
exact
path="/feed"
render={() => (
<Suspense fallback={<div>Loading...<div>}>
<Feed isLogged={isLogged} user={user} {...props} />
</Suspense>
)}
/>
<Route
exact
path="/settings"
render={() => (
<Suspense fallback={<div>Loading...<div>}>
<Settings
isLight={isLight}
setIsLight={setIsLight}
handleClick={handleClick}
showBtn={showBtn}
{...props}
/>
</Suspense>
)}
/>
<Route
render={() => <NotFound />}
/>
</Switch>
There is a lot of repetition here, so it is practical to factor out the suspense into a HOC.
const withSuspense = (WrappedComponent, fallback) => props => (
<Suspense fallback={fallback}>
<WrappedComponent {...props} />
</Suspense>
);
You can either decorate each perspective default export, i.e.
export default withSuspense(Home, <div>Loading...<div>);
App.js
...
<Switch>
<Route exact path="/" render={props => <Home {...props} />} />
or decorate them in your App
const HomeWithSuspense = withSuspense(Home, <div>Loading...<div>);
...
<Switch>
<Route
exact
path="/"
render={props => <HomeWithSuspense {...props} />}
/>
...
</Switch>

In case someone is having the same problem, the actual problem was that some of the components had other components within them which weren't exported as default and that's why they weren't being lazy-loaded.
So if you're having the same problem, you should check the import tree of the component you're trying to lazy-load and make sure every component in this tree is exported as default.
For more information refer to the named exports section in the react docs.
Thanks everyone for your help!

That should work, I would look other problems, like build scripts, or some other piece of code using those same bundles. (e.g. the inheritance thing you mentioned in comments)

Please try this once if above are worked
import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
const Home = lazy(() => import("./components/Home"));
const About = lazy(() => import("./components/About"));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route exact path='/' element={<Home/>}/>
<Route exact path='/about' element={<About/>}/>
</Routes>
</Suspense>
</Router>
);
export default App

There's no need for the whole tree that you're trying to lazy load to have default imports and exports. The component tree with its unique dependencies will be bundled into lazy chunk by default.
For eg.
Component.js
import { x, y } from z
.....
export default Component
main.js
const Component = React.lazy(() => import('Component.js')
Here the main.js chunk will not include code any code from z or
any of the code from Component.js and its unique dependencies
https://webpack.js.org/guides/code-splitting/#dynamic-imports
https://create-react-app.dev/docs/code-splitting/#appjs

Related

useContext returns null value in some components

I have a react component index.js that fetches the user information from a Laravel server through a fetch call. The information is provided to the context UserContext, which is declared in a separate file and imported, near the top-level of the app as follows.
UserContext.jsx
import { createContext } from "react";
const UserContext = createContext(null);
export default UserContext;
const [user, setUser] = useState(null);
useEffect(() => {
// Get logged in user
fetch('/user', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include'
}).then(res => res.json()).then(data => {
setUser(data);
}).catch(err => {
setUser(null)
});
}
return (
<UserContext.Provider value={user}>
<Header/>
<main>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home categories={categories} />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/profile/:id" element={<Profile />} />
<Route path="/profile/:id/edit" element={<EditProfile />} />
<Route path="/profile/:id/registrations" element={<MyRegistrations />} />
<Route path="/posts" element={<Posts />}></Route>
<Route path="/posts/:id" element={<Post categories={categories} />}></Route>
<Route path="/category/:id" element={<Posts />} />
<Route path="/403" element={<Error error={403} />} />
<Route path="/404" element={<Error error={404} />} />
<Route path="/500" element={<Error error={500} />} />
<Route path="*" element={<Error error={404} />} />
</Routes>
</BrowserRouter>
</main>
<Footer/>
</UserContext.Provider>
);
When I try to access user in <Header>, it works as expected. However, in the routes nested in the react-router-dom <Routes>, it returns null.
Header.jsx, Post.jsx declaration to access user
const user = useContext(UserContext);
I suspected that this could be caused because of the context provided by react-router-dom or the nesting, so I tried to pull <Post/> to the top level and disable react-router-dom but it seems to be the same issue.
Post.jsx
import { useState, useEffect, useContext } from 'react';
import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import * as DOMPurify from 'dompurify';
import { Container } from 'react-bootstrap';
import UserContext from '../context/userContext';
export default function Post({ categories }) {
const user = React.useContext(UserContext);
let navigate = useNavigate();
let params = useParams();
const [id, setId] = useState(params.id);
const [post, setPost] = useState(null);
const [registered, setRegistered] = useState(false);
const inCourse = (id, courses) => {
console.log(id, courses);
return courses.filter(course => course.id == id).length > 0;
}
const inEvent = (id, events) => {
return events.filter(event => event.id == id).length > 0;
}
useEffect(() => {
{/* fetch post from api, works correctly */}
}, [id]);
useEffect(() => {
}, [user, id]);
return (
{/* unnecessary jsx */}
);
}

Typescript React - has no properties in common with type 'IntrinsicAttributes'

Learning typescript and trying to convert one of my other react projects to typescript to learn it.
I am getting the error on the routes in my App.tsx file - Type '{ history: History<unknown>; location: Location<unknown>; match: match<any>; staticContext?: StaticContext | undefined; }' has no properties in common with type 'IntrinsicAttributes'.
the name prop is also throwing a typescript error, but for now I commented it out to tackle one problem at a time. Here is my App.tsx.
import React from "react";
import Toaster from "./reusable/Toaster.js";
import { HashRouter, Route, Switch } from "react-router-dom";
import { SocketContext, socket } from "./SocketContext";
import "./scss/style.scss";
const loading = (
<div className="pt-3 text-center">
<div className="sk-spinner sk-spinner-pulse"></div>
</div>
);
// Containers
const TheLayout = React.lazy(() => import("./containers/TheLayout"));
const Login = React.lazy(() => import("./views/auth/Login.js"));
const Logout = React.lazy(() => import("./views/auth/Logout.js"));
const Register = React.lazy(() => import("./views/auth/Register.js"));
const Activate = React.lazy(() => import("./views/auth/Activate.js"));
const ResetPass = React.lazy(() => import("./views/auth/ResetPass.js"));
const Page404 = React.lazy(() => import("./views/page404/Page404"));
const App = () => {
return (
<HashRouter>
<Toaster />
<React.Suspense fallback={loading}>
<SocketContext.Provider value={socket}>
<Switch>
<Route
path="/reset-password"
// name="Reset Password"
render={(props) => <ResetPass {...props} />}
/>
<Route
path="/logout"
// name="Logout"
render={(props) => <Logout {...props} />}
/>
<Route
path="/activate"
// name="Activate"
render={(props) => <Activate {...props} />}
/>
<Route
path="/register"
// name="Register"
render={(props) => <Register {...props} />}
/>
<Route
path="/login"
// name="Login"
render={(props) => <Login {...props} />}
/>
<Route
path="/404"
// name="Not Found!"
render={(props) => <Page404 {...props} />}
/>
<Route
path="/"
// name="Home"
render={(props) => <TheLayout {...props} />}
/>
</Switch>
</SocketContext.Provider>
</React.Suspense>
</HashRouter>
);
};
export default App;
This is a wild guess but is react-router passing in props about the location and history to your components (via the render-props call) but they don't declare that it accepts those properties, so Typescript is telling you that the attempt to push react-router shaped props into components which don't have them will fail.
You need import RouteComponentProps from react-router-dom
import { RouteComponentProps } from 'react-router-dom';
Define custom props for your route
interface RouteProps {
name: string
}
And use it like this on your App component
const App: React.FC<RouteComponentProps<RouteProps>> = () => {
return (
...
<Route
path="/reset-password"
name="Reset Password"
render={(props) => <ResetPass {...props} />}
/>
...
);
};
export default App;
Make sure you have #types/react-router-dom installed and this should fix both the name issue too.

Lazy loading doesn't work when using react-router-dom

Tried every possible solution available on the web. Please Help.
Ran npm run eject
Edited package.json file and tried the recommended solution of adding the below code as per https://reactrouter.com/web/guides/code-splitting.
"babel": {
"presets": [
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-syntax-dynamic-import"
]
}
Below is my code where I use lazy loading. Only the root route ("/") gets loaded. Nothing is loaded when I visit localhost:3000/auth
import React, { useEffect, Suspense } from 'react';
import { connect } from 'react-redux';
import { Redirect, Route, Switch, withRouter } from 'react-router-dom';
import Layout from './components/Layout/Layout';
import Logout from './containers/Auth/Logout/Logout';
import BurgerBuilder from './containers/BurgerBuilder/BurgerBuilder';
import * as actions from './store/actions/index';
const Checkout = React.lazy(() => import('./containers/Checkout/Checkout'));
const Orders = React.lazy(() => import('./containers/Orders/Orders'));
const Auth = React.lazy(() => import('./containers/Auth/Auth'));
const App = (props) => {
useEffect(() => {
props.onTryAutoSignup();
}, []);
let routes = (
<Switch>
<Route
path="/auth"
render={(props) => {
<Auth {...props} />;
}}
/>
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
);
if (props.isAuthenticated) {
routes = (
<Switch>
<Route path="/checkout" render={(props) => <Checkout {...props} />} />
<Route path="/orders" render={(props) => <Orders {...props} />} />
<Route path="/logout" component={Logout} />
<Route path="/auth" render={(props) => <Auth {...props} />} />
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
);
}
return (
<div>
<Layout>
<Suspense fallback={<p>Loading...</p>}>{routes}</Suspense>
</Layout>
</div>
);
};
const mapStateToProps = (state) => {
return {
isAuthenticated: state.auth.token !== null,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onTryAutoSignup: () => dispatch(actions.authCheckState()),
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
My package.json file package.json
My webpack config file webpack.config.js
I have got my mistake.
The webpack or babel config have nothing to do with lazy loading unless you are using Typescript which I'm not.
I had a syntax error in my code which my IDE failed to recognise.
Instead of this
<Route
path="/auth"
render={(props) => {
<Auth {...props} />;
}}
/>
It should have been this
<Route path="/auth" render=(props) => <Auth {...props} /> />

Conditional Route not rendering the redirected Layout

In AppRouter, I have a conditional route with redirect for <AdminLayout/>.
relevant snippet:
<Route
exact
path="/admin"
strict
render={(props) => <AdminLayout {...props} />}
>
{loggedIn ? <Redirect to="/admin/summary" /> : <Login />}
</Route>
If loggedIn is true then, redirect to /admin/summary else redirect it back to <Login/>
The problem is: it is only changing the URL but not rendering the <AdminLayout/>.
Not sure where I am going wrong and what I am missing.
UPDATED PrivateRoute and AppRouter below
AppRouter
import React, { useEffect } from "react";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { createBrowserHistory } from "history";
import { alertActions } from "../actions";
import { history } from "../helpers";
import AdminLayout from "layouts/Admin/Admin.js";
import AuthLayout from "layouts/Auth/Auth.js";
import ResetPassword from "../components/pages/reset-password/ResetPassword";
import MailReset from "../components/pages/reset-password/MailReset";
import PrivateRoute from "../routes/PrivateRoute";
import Dashboard from "views/Dashboard";
const hist = createBrowserHistory();
const AppRouter = () => {
const alert = useSelector((state) => state.alert);
const dispatch = useDispatch();
useEffect(() => {
history.listen((location, action) => {
// clear alert on location change
dispatch(alertActions.clear());
});
}, []);
return (
<Router history={hist}>
<Switch>
{/* <Route path="/admin" render={(props) => <AdminLayout {...props} />} /> */}
<PrivateRoute exact path="/admin">
<Dashboard />
</PrivateRoute>
<Route
path="/auth/login"
render={(props) => <AuthLayout {...props} />}
/>
<Route exact path="/auth/forgotPassword" component={ResetPassword} />
<Route exact path="/auth/mail_reset" component={MailReset} />
<Redirect from="*" to="/auth/login" />
</Switch>
</Router>
);
};
export default AppRouter;
PrivateRoute
import React from "react";
import { Route, Redirect } from "react-router-dom";
import AdminLayout from "../layouts/Admin/Admin";
function PrivateRoute({ component: Component, roles, ...rest }) {
console.log("rest pvt route", ...rest);
return (
<Route
{...rest}
render={(props) => {
console.log("propsssss", props);
// if (!localStorage.getItem('userid')) {
if (!localStorage.getItem("access_token")) {
// not logged in so redirect to login page with the return url
return (
<Redirect
to={{ pathname: "/auth/login", state: { from: props.location } }}
/>
);
}
// logged in so return component
return <AdminLayout {...props} />;
}}
/>
);
}
export default { PrivateRoute };
So trying to explain what its is wrong:
You are setting rendering child and render props that's why children props takes priority here:
<Route
exact
path="/admin"
render={(props) => <AdminLayout {...props} />}
>
{loggedIn ? <Redirect to="/admin/summary" /> : <Login />}
</Route>
Your private route is correct but need to add your layout as well:
return <AdminLayout {...props} /><Component {...props} /></AdminLayout/>;
Inside app route you need to import PrivateRoute component it will look like this:
import PrivateRoute from './PrivateRoute';
const AppRouter = () => {
const alert = useSelector((state) => state.alert);
const loggedIn = useSelector((state) => state.authentication.loggedIn);
const dispatch = useDispatch();
useEffect(() => {
history.listen((location, action) => {
// clear alert on location change
dispatch(alertActions.clear());
});
}, []);
return (
<Router history={hist}>
<Switch>
<PrivateRoute exact path='/admin'>
<YOUR AUTH COMPONENT WHICH YOU WANT TO RENDER />
</PrivateRoute>
<Route
path='/auth/login'
render={(props) => <AuthLayout {...props} />}
/>
<Route exact path='/auth/forgotPassword' component={ResetPassword} />
<Route exact path='/auth/mail_reset' component={MailReset} />
<Redirect from='*' to='/auth/login' />
</Switch>
</Router>
);
};
Here I created demo code of this. Take reference from it: https://codesandbox.io/s/react-router-redirects-auth-forked-6q6o4?file=/example.js

react router "# sign inside route"

i using react-router for my project,
in that there's a problem which is for every route "#" sign is added at the start of every router path..
ex": http://localhost:3000/#/login
i want to remove that # sign but i couldn't able solve it my self.
procedure of my routing is
in app.js im checking the user is signed in or not if not signed in then he will redirect into /login page.(for that also it is showing path as http://localhost:3000/#/login)
below is the app.js
import React, { Component, Fragment } from "react";
import { HashRouter, Route, Switch, Redirect } from "react-router-dom";
// import { renderRoutes } from 'react-router-config';
import "./App.scss";
import { connect } from "react-redux";
import { loadUser } from "./actions/authActions";
const loading = () => (
<div className="animated fadeIn pt-3 text-center">Loading....</div>
);
// Containers
const DefaultLayout = React.lazy(() =>
import("./containers/DefaultLayout/DefaultLayout")
);
// Pages
const Login = React.lazy(() => import("./views/Login/Login"));
const Register = React.lazy(() => import("./views/Register/Register"));
const Page404 = React.lazy(() => import("./views/Page404/Page404"));
const Page500 = React.lazy(() => import("./views/Page500/Page500"));
class App extends Component {
componentDidMount() {
this.props.LOADUSER();
}
render() {
return (
<HashRouter>
<React.Suspense fallback={loading()}>
<Switch>
{!this.props.isAuthenicated ? (
<Fragment>
<Redirect from="*" to="/login" />
<Route
exact
path="/login"
name="Login Page"
render={props => <Login {...props} />}
/>
{/* <Route
exact
path="/register"
name="Register Page"
render={(props) => <Register {...props} />}
/>
<Route
exact
path="/404"
name="Page 404"
render={(props) => <Page404 {...props} />}
/>
<Route
exact
path="/500"
name="Page 500"
render={(props) => <Page500 {...props} />}
/> */}
</Fragment>
) : (
<Route
name="Home"
path="/"
render={props => <DefaultLayout {...props} />}
/>
)}
</Switch>
</React.Suspense>
</HashRouter>
);
}
}
const mapStateToProps = state => ({
isAuthenicated: state.auth.isAuthenicated,
isLoading: state.auth.isLoading,
error: state.error,
token: state.auth.token
});
const mapDispachToProps = dispach => {
return {
//LOGIN: (newUser) => dispach(login(newUser)),
LOADUSER: () => dispach(loadUser())
};
};
export default connect(mapStateToProps, mapDispachToProps)(App);
else he is signed in then im using a component called DefaultLayout Component I will render it.
it has all the routes for other usages which is using routes from routes.js.
below is the DefaultLayout Component
import React, { Component, Suspense } from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import * as router from "react-router-dom";
import { Container } from "reactstrap";
import { logout } from "../../actions/authActions";
import { ToastContainer } from "react-toastify";
import Loader from "react-loaders";
import "react-toastify/dist/ReactToastify.css";
import {
AppHeader,
AppSidebar,
AppSidebarFooter,
AppSidebarForm,
AppSidebarHeader,
AppSidebarMinimizer,
AppBreadcrumb2 as AppBreadcrumb,
AppSidebarNav2 as AppSidebarNav
} from "#coreui/react";
// sidebar nav config
import _navs from "../../_nav";
// routes config
import routes from "../../routes";
import { connect } from "react-redux";
const DefaultHeader = React.lazy(() => import("./DefaultHeader"));
class DefaultLayout extends Component {
state = {
isAuthenicated: true
};
loading = () => <Loader type="ball-triangle-path" />;
signOut(e) {
e.preventDefault();
this.props.history.push("/login");
this.props.LOGOUT();
}
render() {
return (
<div className="app">
<AppHeader fixed>
<Suspense fallback={this.loading()}>
<DefaultHeader onLogout={e => this.signOut(e)} />
</Suspense>
</AppHeader>
<div className="app-body">
<AppSidebar fixed display="lg">
<AppSidebarHeader />
<AppSidebarForm />
<Suspense>
<AppSidebarNav
navConfig={_navs}
{...this.props}
router={router}
/>
</Suspense>
<AppSidebarFooter />
<AppSidebarMinimizer />
</AppSidebar>
<main className="main">
<AppBreadcrumb appRoutes={routes} router={router} />
<Container fluid>
<Suspense fallback={this.loading()}>
<Switch>
{routes.map((route, idx) => {
return route.component ? (
<Route
key={idx}
path={route.path}
exact={route.exact}
name={route.name}
render={props => (
<route.component {...props} {...route.props} />
)}
/>
) : null;
// (
// <Redirect from="*" to="/dashboard" />
// );
})}
<Redirect from="*" to="/" />
</Switch>
</Suspense>
<ToastContainer autoClose={3000} position="bottom-center" />
</Container>
</main>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
isAuthenicated: state.auth.isAuthenicated,
error: state.error
});
const mapDispachToProps = dispach => {
return {
LOGOUT: () => dispach(logout())
};
};
export default connect(mapStateToProps, mapDispachToProps)(DefaultLayout);
example of routes.js also below
const routes =[{
path: "/",
exact: true,
name: "Home",
component: Dashboard
},
{
path: "/user_overview",
name: "Users Overview",
component: Register
}]
for every route it's showing # can anyone help me to resolve that # sign in the route path?
Thank you!
You are using HashRouter this is the purpose of this Router.
Usually one uses it in-order to prevent the server to get those routes.
If you want to use real routes just replace it with BrowserRouter.
Pay attention that your server will need to be able to support those routes.
navigate to some route say /some/page press reload, make sure that your server return your client code.

Resources