简体   繁体   中英

auth0 reactjs redirect to different route if not logged in

I'm learning Auth0 + react and am specifically looking at the example here: https://github.com/auth0-blog/auth0-react-sample

On the home.js page there is a code block:

import React, { Fragment } from "react";

import { Hero, HomeContent } from "../components";


const Home = () => (
  <Fragment>
    <Hero />
    <hr />
    <HomeContent />
  </Fragment>
);

export default Home;

What I want to do is render the JSX (? I think that's the the term) <Hero /> if the user is authenticated and render something that says "User not authenticated for this" if the user is not logged in.

I was able to get the first part working by changing the file to:

import React, { Fragment } from "react";

import { Hero, HomeContent } from "../components";
import ProtectedRoute from "../auth/protected-route";


const Home = () => (
  <Fragment>
    <ProtectedRoute path="/Hero" component={Hero} />
    {/*<Hero />*/}
    <hr />
    <HomeContent />
  </Fragment>
);

export default Home;

However I'm at a loss how to render a "Not logged in" div. I can make a separate view easily enough and make it a route but I'm lost as to how to do the if/else block?

Apologies if silly question, coming from the python world.

Thanks!

#Edit 1: The protected route component is below:

// src/auth/protected-route.js

import React from "react";
import { Route } from "react-router-dom";
import { withAuthenticationRequired } from "@auth0/auth0-react";
import { Loading } from "../components/index";

const ProtectedRoute = ({ component, ...args }) => (
  <Route
    component={withAuthenticationRequired(component, {
      onRedirecting: () => <Loading />,
    })}
    {...args}
  />
);

export default ProtectedRoute;

Based on what you need, we can call the useAuth0 hook again in the Home component to get the auth state. Try the following:

const Home = () => {
  const { isAuthenticated } = useAuth0()
  return (
    <Fragment>
      {isAuthenticated ? <Hero /> : "User not authenticated for this"}
      <hr />
      <HomeContent />
    </Fragment>
  )
}

The useAuth0 hook is actually just a Context API consumer: https://github.com/auth0/auth0-react/blob/master/src/use-auth0.tsx

The context provider Auth0ProviderWithHistory is rendered in index.js and wraps our App component, so we can call the useAuth0 hook anywhere in our App to grab any of the Auth0 state or helper functions.

If you're not across the React Context API, here are the docs: https://reactjs.org/docs/context.html

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