简体   繁体   中英

Setting up protected routes in React with react-router-6

I am using keycloak for my React + Typescript app and I need to setup ProtectedRoutes so that certain paths can only be accessed when the user has logged in. I have the keycloak part working but for some reason, I am unable to pass custom props to the components and the props in the Component is empty.

My react-router-dom version is 6.3.0

Following is what I am trying

function ProtectedRoute({ children, ...rest }: PropsWithChildren<any>) {
  const { keycloak } = useKeycloak()
    if (!keycloak?.authenticated) {
      return <Navigate to="/login" />;
    }
    return children ;
}

Usage

const global = {
    isSomething: isSomethingSelected,
    setSomethingSelected: setsomethingSelected
}

<Routes>
                  
    <Route path='/books' element={<ProtectedRoute global={global}><Books /></ProtectedRoute>}/>

</Routes

Component

export default function Books(props: any) {
    const { global } = props;
  console.log(global); // props is empty
}

Well, in fact you're passing the props to ProtectedRoute and not to Books component.

<Route path='/books' element={<ProtectedRoute><Books global={global} /></ProtectedRoute>}/>

On the other hand, I would make it a little different, if you want the suggestion.

function ProtectedRoute(props: PropsWithChildren<any>) {
  const { keycloak } = useKeycloak();

  if (!keycloak?.authenticated) {
    return <Navigate to="/login" />;
  }

  return (
    <Route {...props} />
  );
}
const global = {
  isSomething: isSomethingSelected,
  setSomethingSelected: setsomethingSelected
}

<Routes>        
  <ProtectedRoute path="/books" element={<Books global={global} />}/>

</Routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM