skip to Main Content

I want to conditionally render my component named Login and Menubar according to the isLogin state.

I want to render either the login page or the Menubar page according to the "isLogin" state. if isLogin is false then render the login page either render the menubar page.
I use the "Ternary" Operator for this.
Now the problem is that when I press the login button in the Login component, the gotoMenu function calls the Handler function which is in App.js and I passed this function as Props in the Login component. It revokes the Handler function, it also changes the isLogin state to true, and renders the Menubar page for a second, and then again Login Page appears. I can’t figure out what happened.

here is App.js Code

import React from 'react'
import Navbar from './components/Navbar';
import Menubar from './components/Menubar';
import Login from './components/Login';
import {
  useState
} from 'react';

const App = () => {
  const [isLogin, setisLogin] = useState(false);
  const Handler = () => {
    console.log("In app");
    setisLogin(true);
  }


  return ( 
    <>
       <Navbar /> 
       {!isLogin 
         ? <Login Handler = {Handler} /> 
         : <Menubar/ >
       }
    </>
  );
}
export default App

Button code in Login component

<button onClick={goTOMenu} className='font-mono  text-white text-4xl text-center'>Login</button>

Login component’s gotoMenu function code :-

const Login = ({ Handler }) => {
  const goTOMenu = () => {
    console.log("switching");
    Handler();
  };
};

2

Answers


  1. You are expecting that if the isLogin is false then it should return Login page,

    if isLogin is false then render the login page either render the
    menubar page.

    Try to change the condition according to your requirement like this,

    return ( 
        <>
           <Navbar /> 
           {isLogin 
             ? <Menubar /> 
             : <Login Handler = {Handler} />
           }
        </>
    );
    
    Login or Signup to reply.
  2. Just tried to recreate your code on CodeSandbox, you can find it here

    The behavior is as expected- clicking the login function invokes the goTOMenu function (as shown ‘switching’ being logged in the console), followed by the Handler function you are passing down as a prop (as shown by the ‘In app’ being console logged).

    You can see that once Login is clicked, the Menubar gets rendered, and not the Login page.

    Not sure if I’m missing something else here, do check and let me know. Happy to help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search