Search code examples
javascriptreactjsbuildreact-router-dom

In build routing is not working like url is changed but content is not changed


In my project I setup routing with this version of "react-router-dom" : "^6.7.0" so when I run the project in localhost without creating build then it's working fine. But when I create build and then after surve that build it started but like project run on http://localhost:51746/ but in route configration for private route it redirect to the http://localhost:51746/login so URL is changin but content is not loaded whole page is shown as blank

here is some screen short and code when build is run and this page is shown after refreshing the page getting the ui

below is code for App.js

import React, { useEffect, useState } from "react";
import {
    Route,
    Routes,
    BrowserRouter, Navigate
} from "react-router-dom";
import { useSelector } from "react-redux";
import { ProSidebarProvider } from "react-pro-sidebar";

import { getAuthToken, getFromStorage } from "./utils/common";
import TheSidebar from "./containers/TheSidebar/TheSidebar";
import { AuthProvider } from "./context";
import { config } from "./utils/config";
import { io } from "socket.io-client";
import {Loading} from "./reusable";

import 'bootstrap/dist/css/bootstrap.min.css';
import "./SASS/app.scss";

const Dashboard = React.lazy(() => import('./views/Dashboard'));
const AllApps = React.lazy(() => import("./views/AllApps"));
const AllAppsEdit = React.lazy(() => import("./views/AllApps/Edit"));
const AllAppsView = React.lazy(() => import("./views/AllApps/View"));
const Platform = React.lazy(() => import("./views/Platform"));
const Notification = React.lazy(() => import("./views/Notification"));
const Login = React.lazy(() => import("./views/Login"));
const Profile = React.lazy(() => import("./views/Profile"));
const Category = React.lazy(() => import("./views/Category"));
const UserList = React.lazy(() => import("./views/UserList"));
const TheLayout = React.lazy(() => import('./containers/TheLayout'));
const TestKeys = React.lazy(() => import('./views/TestKeys'));
const Console = React.lazy(() => import('./views/Console'));
const ConsoleCreateEdit = React.lazy(() => import('./views/Console/Create'));
const DownloadAppsChart = React.lazy(() => import('./views/DownloadAppsChart'));
const OuterKeysAccess = React.lazy(() => import('./views/Dashboard/components/OuterKeysAccess'));
const ViewAccountAppList = React.lazy(() => import('./views/Dashboard/components/ViewAccountAppList'));

const PublicRoutes = ({ children }) => {
    const token = useSelector(x => x?.authorization)?.access_token || getAuthToken();
    return token ? <Navigate replace to="/" /> : children
}

function PrivateRoute({ name, children }) {
    const token = useSelector(x => x?.authorization)?.access_token || getFromStorage('token');
    if (!token) {
        return <Navigate to="/login" />
    }
    return <TheLayout name={name}>{children}</TheLayout>;
}

global.defaultImg = 'https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg';

const App = () => {

    const token = useSelector(x => x?.authorization)?.access_token || getAuthToken();
    const [callNotificationApi, setCallNotificationApi] = useState({});

    useEffect(() => {
        const socket = io(config.SOCKET_BASE, {
            auth: {
                token: token
            }
        });

        let isConnected = false;

        socket.on('connect', () => {
            isConnected = true;
        });

        socket.on('call-notification', (receivedMessage) => {
            if (isConnected) {
                if (JSON.parse(receivedMessage)) {
                    console.log('JSON.parse(receivedMessage)', JSON.parse(receivedMessage))
                    setCallNotificationApi(JSON.parse(receivedMessage))
                }
            } else {
                setTimeout(() => {
                    if (JSON.parse(receivedMessage)) {
                        console.log('JSON.parse(receivedMessage)', JSON.parse(receivedMessage))
                        setCallNotificationApi(JSON.parse(receivedMessage))
                    }
                }, 500);
            }
        });
        return () => {
            socket.disconnect();
        };
    }, []);

    return (
        <>
            <React.Suspense fallback={<Loading/>}>
                <AuthProvider callNotificationApi={callNotificationApi} setCallNotificationApi={setCallNotificationApi}>
                    <ProSidebarProvider>
                        <BrowserRouter>
                            <div className={`${token ? "flex-row min-vh-100 h-100 d-flex" : ""} h-100`}>
                                {token && <div
                                    style={{
                                        display: "flex",
                                    }}
                                >
                                    <TheSidebar />
                                </div>}
                                <Routes>
                                    <Route
                                        path="/account"
                                        exact='true'
                                        element={
                                            <PrivateRoute name='Play store Account'>
                                                <Dashboard />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        path="/account/view"
                                        exact='true'
                                        element={
                                            <PrivateRoute name='View Application List'>
                                                <ViewAccountAppList />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/all-apps"
                                        element={
                                            <PrivateRoute name='All Application List'>
                                                <AllApps />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/all-console"
                                        element={
                                            <PrivateRoute name='All Console List'>
                                                <Console />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/all-console/create"
                                        element={
                                            <PrivateRoute name='Create Console'>
                                                <ConsoleCreateEdit />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/all-console/edit/:id"
                                        element={
                                            <PrivateRoute name='Edit Console'>
                                                <ConsoleCreateEdit />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/all-apps/edit"
                                        element={
                                            <PrivateRoute name='Edit Application'>
                                                <AllAppsEdit />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/all-apps/view"
                                        element={
                                            <PrivateRoute name='View Application'>
                                                <AllAppsView />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/notification"
                                        element={
                                            <PrivateRoute name='Notification'>
                                                <Notification />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/platform"
                                        element={
                                            <PrivateRoute name='Platform'>
                                                <Platform />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/profile"
                                        element={
                                            <PrivateRoute name='Profile'>
                                                <Profile />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/category"
                                        element={
                                            <PrivateRoute name="Category's">
                                                <Category />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/user-list"
                                        element={
                                            <PrivateRoute name="User List">
                                                <UserList />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/"
                                        element={
                                            <PrivateRoute name="User List">
                                                <DownloadAppsChart />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/test-keys"
                                        element={
                                            <PrivateRoute name="Test Keys">
                                                <TestKeys />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        exact='true'
                                        path="/outer-keys"
                                        element={
                                            <PrivateRoute name="Outer Keys">
                                                <OuterKeysAccess />
                                            </PrivateRoute>
                                        }
                                    />
                                    <Route
                                        path="/login"
                                        exact='true'
                                        element={
                                            <PublicRoutes>
                                                <Login />
                                            </PublicRoutes>
                                        }
                                    />
                                    <Route
                                        path="*"
                                        element={
                                            <Navigate to="/" />
                                        }
                                    />
                                </Routes>
                            </div>
                        </BrowserRouter>
                    </ProSidebarProvider>
                </AuthProvider>
            </React.Suspense>
        </>
    )
};

export default App;

here is login component

import {useContext, useState} from "react";
import {useDispatch} from "react-redux";
import {Checkbox, Col, Row} from "antd";
import {UserOutlined} from "@ant-design/icons";
import {useNavigate} from "react-router-dom";
import {GreenButton, TextField} from "../../reusable";
import LoginImage from '../../assets/images/login1.jpg';
import {login} from "../../redux/modules/Auth/authActions";
import {errorMessage, setCookie, successMessage, validateEmail, validatePassword} from "../../utils/common";
import {authContext} from "../../context";
import "./login.scss"

const Login = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const {setAuthData} = useContext(authContext);
    const [error, setError] = useState('');
    const [userDetail, setUserDetail] = useState({
        email: '',
        password: '',
        rememberMe: false
    });

    const HandleLogin = () => {
        const onSuccess = response => {
            successMessage(`Login successfully.`);
            if (userDetail?.rememberMe) {
                for (let key in response) {
                    setCookie(key, response[key]);
                }
            }
            setAuthData(response?.access_token);
            navigate('/', {replace: true});
        };
        const onFail = err => {
            errorMessage(err.data?.title || err.data?.message || "Error while Login.");
        };
        if (validateEmail(userDetail?.email) && validatePassword(userDetail?.password))
            dispatch(login({
                data: userDetail, onSuccess, onFail
            }));
        else
            setError('Please Enter Valid Email or Password');
    };

    return (
        <div className='h-100 d-flex align-items-center'>
            <div className="login-card w-100">
                <Row>
                    <Col xs={24} xl={12} md={12} lg={12} sm={12} className="image-div-login w-100 p-0">
                        <img alt={"login image"} className='w-100 h-100' src={LoginImage}/>
                    </Col>
                    <Col xs={24} xl={12} md={12} lg={12} sm={12} className="form-div">
                        <div className="sign-in d-flex h-100 flex-column justify-content-center container p-5">
                            <div className="sing-in-title fw-600">
                                Sign In
                            </div>
                            <div>
                                <TextField errorMsg='Email is required' value={userDetail?.email} required
                                           placeholder='Enter Email'
                                           label='Email'
                                           onChange={(e) => setUserDetail({
                                               ...userDetail,
                                               email: e?.target?.value.replace(/\s/g, '')
                                           })}
                                           name='email' type='email'
                                           prefix={<UserOutlined/>}
                                />
                                <TextField value={userDetail?.password} type='password' required
                                           placeholder='Enter password' errorMsg='Please Enter Valid Password.'
                                           label='Password'
                                           onChange={(e) => setUserDetail({
                                               ...userDetail,
                                               password: e?.target?.value.replace(/\s/g, '')
                                           })}
                                           name='password'/>
                            </div>
                            <small className="text-left text-danger">{error || ""}</small>
                            <div className="mt-22 d-flex justify-content-between align-items-center">
                                <Checkbox className="fw-400"
                                          onChange={(e) => {
                                              setUserDetail({
                                                  ...userDetail,
                                                  rememberMe: e?.target?.checked
                                              })
                                          }}
                                >Remember me</Checkbox>
                            </div>
                            <div className="mt-7 d-flex">
                                <GreenButton bg='bg-light-purple' className='mb-0 py-2 px-3'
                                             disabled={!userDetail?.email || !userDetail?.password}
                                             onClick={() => HandleLogin()}>Sign In</GreenButton>
                            </div>
                        </div>
                    </Col>
                </Row>
            </div>
        </div>
    )
};
export default Login;

package.json

"dependencies": {
    "@ant-design/icons": "^5.0.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "antd": "^5.1.6",
    "apexcharts": "3.40.0",
    "axios": "^1.2.4",
    "bootstrap": "^5.2.3",
    "keymirror": "^0.1.1",
    "lodash": "^4.17.21",
    "moment": "^2.29.4",
    "react": "^18.2.0",
    "react-apexcharts": "^1.4.0",
    "react-beautiful-dnd": "^13.1.1",
    "react-dom": "^18.2.0",
    "react-google-charts": "^4.0.0",
    "react-json-tree": "^0.18.0",
    "react-pro-sidebar": "^1.0.0",
    "react-redux": "^8.0.5",
    "react-router-dom": "^6.7.0",
    "react-scripts": "5.0.1",
    "redux": "^4.2.0",
    "redux-actions": "^2.6.5",
    "redux-saga": "^1.2.2",
    "socket.io-client": "^4.6.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
    "redux-logger": "^3.0.6",
    "sass": "^1.57.1"
  }

I tried to change the version of react-router-dom also first it's working so remove the last commit and checkd. Moreover try to run without private and public route directly set the route and also used hasRouter but not getting the issue resolved. Expected the component get loaded.


Solution

  • You have to change react-router-dom version to 6.3.0 it will work perfectly. In the latest version there is some issue