Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default route always execute in react router

I am working on a project where I am using the strikingDash template. Here I face some issues of routing while changing the routes from URL.

auth.js

import React, { lazy, Suspense } from "react"
import { Spin } from "antd"
import { Switch, Route, Redirect } from "react-router-dom"
import AuthLayout from "../container/profile/authentication/Index"

const Login = lazy(() =>
  import("../container/profile/authentication/overview/SignIn")
)
const SignUp = lazy(() =>
  import("../container/profile/authentication/overview/SignUp")
)
const ForgetPassword = lazy(() =>
  import("../container/profile/authentication/overview/ForgetPassword")
)
const EmailConfirmation = lazy(() =>
  import("../container/profile/authentication/overview/EmailConfirmation")
)
const VerificationPage = lazy(() =>
  import("../container/profile/authentication/overview/VerificationPage")
)

const NotFound = () => {
  console.log("NOT FOUND")
  return <Redirect to="/" />
}

const FrontendRoutes = () => {
  return (
    <Switch>
      <Suspense
        fallback={
          <div className="spin">
            <Spin />
          </div>
        }
      >
        <Route exact path="/verification" component={VerificationPage} />
        <Route exact path="/email-confirmation" component={EmailConfirmation} />
        <Route exact path="/forgetPassword" component={ForgetPassword} />
        <Route exact path="/signup" component={SignUp} />
        <Route exact path="/" component={Login} />
        <Route component={NotFound} />
      </Suspense>
    </Switch>
  )
}

export default AuthLayout(FrontendRoutes)

App.js

import React, { useEffect, useState } from "react";
import { hot } from "react-hot-loader/root";
import { Provider, useSelector } from "react-redux";
import { ThemeProvider } from "styled-components";
import { BrowserRouter as Router, Redirect, Route } from "react-router-dom";
import { ConfigProvider } from "antd";
import store from "./redux/store";
import Admin from "./routes/admin";
import Auth from "./routes/auth";
import "./static/css/style.css";
import config from "./config/config";
import ProtectedRoute from "./components/utilities/protectedRoute";

const { theme } = config;

const ProviderConfig = () => {
  const { rtl, isLoggedIn, topMenu, darkMode } = useSelector(state => {
    return {
      darkMode: state.ChangeLayoutMode.data,
      rtl: state.ChangeLayoutMode.rtlData,
      topMenu: state.ChangeLayoutMode.topMenu,
      isLoggedIn: state.Authentication.login,
    };
  });

  const [path, setPath] = useState(window.location.pathname);

  useEffect(() => {
    let unmounted = false;
    if (!unmounted) {
      setPath(window.location.pathname);
    }
    // eslint-disable-next-line no-return-assign
    return () => (unmounted = true);
  }, [setPath]);

  return (
    <ConfigProvider direction={rtl ? "rtl" : "ltr"}>
      <ThemeProvider theme={{ ...theme, rtl, topMenu, darkMode }}>
        <Router basename={process.env.PUBLIC_URL}>
          {!isLoggedIn ? <>{console.log("INSIDE PUBLIC")}<Route path="/" component={Auth} /></> : <ProtectedRoute path="/admin" component={Admin} />}
          {isLoggedIn && (path === process.env.PUBLIC_URL || path === `${process.env.PUBLIC_URL}/`) && (
            <Redirect to="/admin" />
          )}
        </Router>
      </ThemeProvider>
    </ConfigProvider>
  );
};

function App() {
  return (
    <Provider store={store}>
      <ProviderConfig />
    </Provider>
  );
}

export default hot(App);

Whenever I change the URL to another route as I described above in Frontend Routes. Then it will always print console statements like these:

INSIDE PUBLIC
NOT FOUND
INSIDE PUBLIC
NOT FOUND

Expected Behaviour: Whenever I update the URL it will render the component according to the switch case and return it back

Actual Behaviour: Whenever I update the URL it will render the component as well as the default component. I think Switch here renders multiple components, but I don't know why.

like image 455
Hassam Saeed Avatar asked Sep 13 '21 12:09

Hassam Saeed


People also ask

How do I set default route in react router?

Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!

Why is routes used in react router?

ReactJS Router is mainly used for developing Single Page Web Applications. React Router is used to define multiple routes in the application. When a user types a specific URL into the browser, and if this URL path matches any 'route' inside the router file, the user will be redirected to that particular route.

What is exact path in react router?

React router does partial matching, so /users partially matches /users/create , so it would incorrectly return the Users route again! The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

How is react router different from conventional routing?

React Router vs Conventional Routing: React Router is a library for React that provides routing functionality. It is different from conventional routing in a few ways. First, React Router is declarative. This means that you specify what you want your route to look like, rather than specifying how to get there.

How to set a default route in react router?

In this tutorial, you will learn to set a default Route in React Router so that all the incorrect routes get redirected to the default route To set the default Route, you have to use <Redirect /> component from the react-router-dom library. Next, include the <Redirect /> component and pass the default route /home to the to attribute.

How does routing work in React Native?

The routing works by comparing the URL against the specified list of routes in our React app. Each route is linked to a <Route> component where we have configured the complete routing configuration. In this guide, you will learn how to get started with routing and redirect the default route to /home.

Can I use React router for a single page application?

The answer is no. React Router – like the name implies – helps you route to/navigate to and render your new component in the index.html file. So as a single page application, when you navigate to a new component using React Router, the index.html will be rewritten with the component's logic.

How does react router work?

In React, the page contents are created from our components. So what React Router does is intercept the request being sent to the server and then injects the contents dynamically from the components we have created.


Video Answer


2 Answers

I just resolved the issue by moving the Switch Tag inside the Suspense tag in the auth.js file.

like image 161
Hassam Saeed Avatar answered Oct 23 '22 01:10

Hassam Saeed


The problem should be in the order of your pages: the root path works as a collector of all the pages, you should try to add the exact keyword to the Router path. Here the reference for the differences between the different notations.

<Route exact path="/" component={Login} />
like image 1
aaandri98 Avatar answered Oct 23 '22 03:10

aaandri98