Skip to content
Advertisement

Make page only accessible if logged in – React

const HomePage = ({ onPageOpen, history, match, receiveToken }) => {
   useEffect(() => {
     onPageOpen();
     if (match.params.resetToken) receiveToken(match.params.resetToken);
   }, []);

   return (
     <BaseMarkUp history={history}>
        <ColumnContainer>
         <LeftColumn>
              <Explore />
              <Tour />
              <News />
          </LeftColumn>
          <RightColumn>
             <HostelReviews />
          </RightColumn>
       </ColumnContainer>
     </BaseMarkUp>
   );
};

Hello, please I,m a beginner in react. and I need help in knowing how to approach this challenge in the snippet above, is my homepage.

my goal now is to make only explore and tour components to visible when user is logged out. so when the users visit the homepage the components will be displayed but when logged in, the components wont be visible.

please I just need steps/guide/advise on how to achieve my intent.

thank you.

Advertisement

Answer

I guess there are 2 easy ways of doing it,

  1. you open the page only when you have figured out that the user is a registered user (recommended way)
  2. supposedly you have opened the page now you have to block some/whole of the view for an unregistered user.(not soo recommended but depends on use case)

to achieve first you have to make some sort of middle-ware (it can be a component, action, or even just function) which will get/verify the token/key you are using to identify the user

// needed imports
const checkedLoggedIn = ()=>{
   // deciding code for registered user
   return (
        {loggedIntoken ? <HomePage ...props/> : <>fallback elem</>}
   )
}

In the second approach, I guess you are using the second one in ur snippet, after u get the deciding token u can hide/show whatever u like

return (
    <BaseMarkUp history={history}>
      <ColumnContainer>
        <LeftColumn>
          <Explore />
          <Tour />
          <News />
        </LeftColumn>
       {loggedIntoken &&  
         <RightColumn>
          <HostelReviews />
        </RightColumn>}
      </ColumnContainer>
    </BaseMarkUp>
  );
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement