Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle(show/hide) components onClick in single page React component useState

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;
like image 826
ckingchris Avatar asked Nov 16 '25 08:11

ckingchris


1 Answers

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.

like image 63
Navid Zarepak Avatar answered Nov 18 '25 21:11

Navid Zarepak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!