As shown in the Flowchart ( Flowchart ), I want to hide the Header component if Main component renders the Login component . But if the Main component renders the Home component , I want to display the Header component .
This is App.js file:
import React from 'react' import Header from 'Header' import Main from 'Main' import Footer from 'Footer' function App() { return ( <div className="App"> <Header /> <Main /> <Footer /> </div> ) } export default App;
This is Main.js file:
import React from 'react' import Home from './Home' import Login from './Login' function Main() { let user = true //Toggled by users return ( <div> { user? ( <Home /> ): ( <Login /> ) } </div> ) } export default Main
Putting the Header Component in Home itself will not solve the problem as I have to add much more pages and adding a Header component in every page doesn't seem efficient.
That's a use case of lifting the state up , here your user
state should be in the scope of Header
and Main
.
Then just pass the user
( isLogged
in the example) to Main
, via props or Context API.
function Main({ isLogged, toggleLogin }) {
return (
<div>
<button onClick={toggleLogin}>toggle</button>
{isLogged ? <>Home</> : <>Login</>}
</div>
);
}
function App() {
const [isLogged, toggle] = useReducer((p) => !p, false);
return (
<div className="App">
{!isLogged && <>Header</>}
<Main isLogged={isLogged} toggleLogin={toggle} />
<>Footer</>
</div>
);
}
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.