0

I am learning react-router protected routes. I am setting up a page with just one button that can sign in and sign out a fake user.

If I try to visit the path "/" in the root component below, then I should just see a "Sign In" button. Except I only see the first two console logs and then the error.

The error looks like as follows

DevTools failed to load source map: Could not load content for webpack://parier/node_modules/react-router/esm/react-router.js.map: Fetch through target failed: Unsupported URL scheme; Fallback: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

Here is my Root.js

  const [user, setUser] = React.useState(null);

  const handleLogin = () => setUser({
    id: '2',
    name: "Temporary Marker",
    isAuthenticated: true
  });const handleLogout = () => setUser(null);
  console.log("<ROOT>: User before render is: ");
  console.log(user);

  return(
    <div className="site">

      <Switch>
        <Route exact path={"/demo/"} component={Demo}/>
        <Route exact path={"/home/"} component={Home}/>
        <Route element={<ProtectedRoute user={user} />}>
          <Route path="play" element={<Play />} />
        </Route>
        <Route path={"/"} render={() =>
          <div>
            Default page
            <div>
              {user ? (
              <button onClick={handleLogout}>Sign Out</button>
                ) : (
              <button onClick={handleLogin}>Sign In</button>
              )}
            </div>
          </div>
          }
        />
        <Route path="*" element={<p>There's nothing here: 404!</p>} />
      </Switch>
    </div>
  )

}

export default Root;

and here is the ProtectedRoute.js component

import react from 'react';
import { Routes, Route, Link} from 'react-router-dom';

const ProtectedRoute = ({ user, redirectPath = '/', children }) => {
  if (!user) {
    console.log("<PROTECTEDROUTE>: User is not defined. Redirecting to / path");
    return <Link to={redirectPath} replace />;
  }

  return children;
};

export default ProtectedRoute;

What am I doing wrong?

Thanks

user1933205
  • 300
  • 4
  • 12
  • 1
    What version of `react-router-dom` are you trying to use? The code is mixing RRD v5 and v6 components and APIs. Does this help answer your question about protected route implementations? https://stackoverflow.com/questions/66289122/how-to-create-a-protected-route-with-react-router-dom – Drew Reese Feb 21 '23 at 19:45
  • react:17.0.1 and react-router-dom: 5.3.0. Let me check that answer. – user1933205 Feb 21 '23 at 20:06
  • RRDv5, ok, so `Routes` is a v6 component that replaced the `Switch` component, and the `Route` components won't have an `element` prop, `element` is a v6 `Route` prop. – Drew Reese Feb 21 '23 at 20:07
  • 1
    So the mistake I am making is I am using v6 syntax with v5. Will take care of that. – user1933205 Feb 22 '23 at 17:47

0 Answers0