I'm new in react, developing a web page as a project, I want when a user open my web page, he will have only Login and Registration component will be there, and NO header or navigation bar will be there, after user successfully login then he will have a header, navbar and other components, and all the Link, Route and Routes will be there, I am unable to understand what to render in App.js, that is my App.js code, in Login component there is Login & registration form. From Login I render Dashboard(Home page).
How to do that any idea ?
import './App.css';
import {Login} from "./loginPage";
function App() {
return (
<>
<Login/>
</>
);
}
export default App;
CodePudding user response:
You can conditionally render elements. For example, let's say you have some state value:
const [showLogin, setShowLogin] = useState(true);
Then you can use that value to conditionally render one thing or the other:
return (
<>
{showLogin ? <Login/> : <Dashboard/>}
</>
);
So in this case when showLogin
is true
then the <Login/>
component renders, otherwise the <Dashboard/>
component renders.
The question then becomes...
What state value will you use and how will you define your condition?
That part is really up to you. Whatever state is being modified by <Login/>
to indicate that the user has successfully logged in, that's the state you would examine in your condition to determine if the user should see the login prompt or the dashboard interface (or whatever you're showing).
That <Dashboard/>
can of course be anything. For example, if you're using a routing system, you might render that instead:
return (
<>
{showLogin ? <Login/> :
<Router>
<!-- your routes here, etc. -->
</Router>
}
</>
);
Any JSX hierarchy will work, just like it would work anywhere else in the JSX.
CodePudding user response:
Here you can create a state called "loggedIn" or anyting or your choice. and add condition (you can use ternary operator) for if its true then render the component.
const [loggedIn, setLoggedIn] = useState(false);
{loggedIn ? <Navbar />: ""}
{loggedIn ? <Header /> : ""}
This way even when the session expires and user is logged out u just have to change one state and these components will be hidden again.