I currently use react-router-dom to separate routing for authenticated/non-authenticated people. But Element has an error for missing the properties.
How can withoutAuth() work for authentication routes?
Type '() => Element' is missing the following properties from type 'ReactElement<any, string | JSXElementConstructor>': type, props, key
function App() {
return (
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/" element={withoutAuth(<Signup />)} />
</Routes>
</AuthProvider>
</BrowserRouter>
);
}
const withoutAuth = (Element: ElementType) =>
function WithoutAuth() {
const { currentFBUser } = useAuthContext()
if (currentFBUser) {
return <Navigate to="/dashboard" />
}
return <Element />
}
You don't generally pass JSX literals to Higher Order Components, and the element prop takes a JSX literal instead of a reference to a React component.
// (1) Create a new decorated component
const SignUpWithoutAuth = withoutAuth(Signup);
function App() {
return (
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
// (2) Pass the new decorated component as JSX to `element` prop
<Route path="/" element={<SignUpWithoutAuth />} />
</Routes>
</AuthProvider>
</BrowserRouter>
);
}
This being said, it would be more conventional to implement as a wrapper component than a HOC in RRDv6.
Example:
function WithoutAuth({ children }) {
const { currentFBUser } = useAuthContext()
if (currentFBUser) {
return <Navigate to="/dashboard" />
}
return children;
}
function App() {
return (
<BrowserRouter>
<AuthProvider>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route
path="/"
element={(
<WithoutAuth>
<Signup />
</WithoutAuth>
)}
/>
</Routes>
</AuthProvider>
</BrowserRouter>
);
}
Either should work.