Skip to content

Commit 5adfd17

Browse files
docs: fix withAuthenticationRequired usage pattern in react-router example
1 parent cb56151 commit 5adfd17

1 file changed

Lines changed: 21 additions & 7 deletions

File tree

EXAMPLES.md

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -170,12 +170,26 @@ import React from 'react';
170170
import { Route, BrowserRouter, Routes, useNavigate } from 'react-router-dom';
171171
import { Auth0Provider, withAuthenticationRequired } from '@auth0/auth0-react';
172172
import Profile from './Profile';
173+
import Settings from './Settings';
173174

174-
const ProtectedRoute = ({ component, ...args }) => {
175-
const Component = withAuthenticationRequired(component, args);
176-
return <Component />;
175+
// Pattern 1: Direct usage at module level
176+
const ProtectedProfile = withAuthenticationRequired(Profile, {
177+
onRedirecting: () => <div>Redirecting to login...</div>,
178+
});
179+
180+
// Pattern 2: Factory pattern (use when you need router hooks in the wrapper)
181+
const createProtectedRoute = (Component, options) => {
182+
const ProtectedComponent = withAuthenticationRequired(Component, options);
183+
return () => {
184+
const navigate = useNavigate(); // Can use hooks here if needed
185+
return <ProtectedComponent />;
186+
};
177187
};
178188

189+
const ProtectedSettings = createProtectedRoute(Settings, {
190+
onRedirecting: () => <div>Redirecting to login...</div>,
191+
});
192+
179193
const Auth0ProviderWithRedirectCallback = ({ children, ...props }) => {
180194
const navigate = useNavigate();
181195
const onRedirectCallback = (appState) => {
@@ -200,17 +214,17 @@ export default function App() {
200214
>
201215
<Routes>
202216
<Route path="/" exact />
203-
<Route
204-
path="/profile"
205-
element={<ProtectedRoute component={Profile} />}
206-
/>
217+
<Route path="/profile" element={<ProtectedProfile />} />
218+
<Route path="/settings" element={<ProtectedSettings />} />
207219
</Routes>
208220
</Auth0ProviderWithRedirectCallback>
209221
</BrowserRouter>
210222
);
211223
}
212224
```
213225

226+
> **Note:** Always call `withAuthenticationRequired` at the module level, not inside a component's render function. Calling HOCs inside render creates a new component on each render, causing unmount/remount cycles that break React Router's blockers and other stateful features.
227+
214228
See [react-router example app](./examples/cra-react-router)
215229

216230
## Protecting a route in a Gatsby app

0 commit comments

Comments
 (0)