Home > Software design >  Am not able to find the Redirect and is not working in react app
Am not able to find the Redirect and is not working in react app

Time:08-14

Redirect is not working in my react-router-dom; when am trying to import and use redirect in the app - I am getting the following error when running npm run start in the terminal. - Attempted import error: 'Redirect' is not exported from 'react-router-dom'.

 import { Route, Redirect } from "react-router-dom";

    const PrivateRoute = ({ ...rest }) => {
      const { auth } = useSelector((state) => ({ ...state }));

      return auth && auth.token ? <Route {...rest} /> : <Redirect to="/login" />;
    };

    export default PrivateRoute;

CodePudding user response:

import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import TopNav from "./components/TopNav";
import PrivateRoute from "./components/PrivateRoute";
// components
import Home from "./booking/Home";
import Login from "./auth/Login";
import Register from "./auth/Register";
import Dashboard from "./user/Dashboard";

function App() {
  return (
    <BrowserRouter>
      <TopNav />
      <ToastContainer position="top-center" />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        <PrivateRoute path="/dashboard" element={<Dashboard />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

CodePudding user response:

So the new react-router-dom version 6 does not have Redirect as an exported member. But there is one similar component that you case use that is Navigate:

import { Route, Navigate } from "react-router-dom";

const PrivateRoute = ({ ...rest }) => {
  const { auth } = useSelector((state) => ({ ...state }));

  return auth && auth.token ? <Route {...rest} /> : <Navigate to="/login" replace={true} />;
};

export default PrivateRoute;

you can read more about that: https://reactrouter.com/docs/en/v6/components/navigate

I have created similar Protected Route component that you can use:

Protected Route:

const PrivateRoutes = ({ component: Component }) => {
  const navigate = useNavigate();
  const { auth } = useSelector((state) => ({ ...state }));

  useEffect(() => {
    if (!(auth && auth.token) ) {
      navigate("/");
    }
  }, [auth]);

  if (auth && auth.token) {
    return <>{Component}</>;
  }
  return <></>;
};

export default PrivateRoutes;

Then you can use this like this:

 <Route
    path="/contacts"
    key="AllContacts"
    element={<PrivateRoute component={<AllContacts />} />}
  />
  • Related