How do you toggle between components in the single page case below? Ideally, when you click the menu-item the associated component will show and the others will hide.
React
import React, { useState } from 'react';
import About from "./components/About";
import Projects from "./components/Projects";
import Contact from "./components/Contact";
const App = () => {
// Toggle state(s) here?
// Toggle function(s) here?
return (
<div className="nav">
<ul className="menu">
<li className="menu-item">About</li>
<li className="menu-item">Projects</li>
<li className="menu-item">Contact</li>
</ul>
</div>
<div className="container">
<About />
<Projects />
<Contact />
</div>
)
};
export default App;
A simple way is to render a component based on the current state and change the state to render another component:
import React, { useState } from 'react';
import About from "./components/About";
import Projects from "./components/Projects";
import Contact from "./components/Contact";
const App = () => {
const [page, setPage] = useState("about")
return (
<div className="nav">
<ul className="menu">
<li className="menu-item" onClick={() => setPage("about")}>About</li>
<li className="menu-item" onClick={() => setPage("projects")}>Projects</li>
<li className="menu-item" onClick={() => setPage("contact")}>Contact</li>
</ul>
</div>
<div className="container">
{page === "about" && <About />}
{page === "projects" && <Projects />}
{page === "contact" && <Contact />}
</div>
)
};
export default App;
You probably want to make it a little cleaner but you have the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With