moussesj94
moussesj94

Reputation: 505

React Router v6 Route element cannot get Context value

I'm using React 17.0.2, react-router-dom 6.0.2 in my app right now.

I try to use react Context and Route to add authenticate on routes.

In App.js I can get value from AuthContext

...

const { authState, authReducer } = useContext(AuthContext);
    
<Routes>
    <Route element={PrivateRoute}>
         <Route path="/dashboard/*" element={<MainLayout />} />
    </Route>
    <Route>
        <Route path="/auth/*" element={<EmptyLayout />} />
    </Route>
    <Route path="*" element={NotFound} />
</Routes>
...

but in PrivateRoute I got undefined

const {authState, authReducer} = useContext(AuthContext);

const {state, dispatch} = authState;
const ele = state.login === true ? <Outlet /> : <Navigate to="/login" replace />;
return <Route path={path} element={ele} />;

In this case, how could I get AuthContext in PrivateRoute?

Thank you

Upvotes: 3

Views: 3219

Answers (1)

Drew Reese
Drew Reese

Reputation: 203333

You are not passing JSX to the route's element props. The layout should render the private route component (and outlet for nested routes).

<Routes>
  <Route
    path="/dashboard/*"
    element={(
      <MainLayout>
        <PrivateRoute />
      </MainLayout>
    )}
  >
    ... protected children subroutes ...
  </Route>
  <Route>
    <Route path="/auth/*" element={<EmptyLayout />} />
  </Route>
  <Route path="*" element={<NotFound />} />
</Routes>

Route components can be only children of a Routes component, so PrivateRoute cannot render one, it just needs to render out either the Outlet for the nested routes or the Navigation for the redirect.

const { authState } = useContext(AuthContext);
const { state, dispatch } = authState;

return state.login ? <Outlet /> : <Navigate to="/login" replace />;

Upvotes: 1

Related Questions