I have a simple toggle using hooks to show/hide sidebar. The toggle button works fine as far as showing and hiding sidebar is concerned. When I click on the toggle button it opens the sidebar. And when I click on any of the link from the side bar, the link takes me to the destined page. But now when I click on the toggle button to open the sidebar, instead of staying on the same page it navigates to the default page.
This is the User page
function User() {
const [isOpen, setIsopen] = useState(false);
const ToggleSidebar = () => {
!isOpen ? setIsopen(true) : setIsopen(false);
}
return (
<div className='userheader'>
<div className='usercontainer'>
<div className='signout-btn-position' >
<SignOut />
</div>
<div className={`sidebar ${isOpen ? 'active' : ''}`}>
<div className="sd-header">
<h4 className="mb-0">Sidebar Header</h4>
</div>
<div className="sd-body">
<ul>
<li>{userName ? <div id='username'><FaUserCircle style={{ marginBottom: '4px', marginRight: '4px' }} />{userName}</div> : "Guest User"}</li>
<i><a href='/user/anesthesiatheory' className='link-btn' >Anesthesia</a></i>
<i><a href='/user/anesthesiatheory' className='link-btn' >Integaumentary</a></i>
<i><a href='/user/anesthesiatheory' className='link-btn' >Musculoskeletal</a></i>
<i><a href='/user/anesthesiatheory' className='link-btn' >Cardio & Respiratory</a></i>
</ul>
</div>
</div>
<Link className="btn" onClick={ToggleSidebar}><FaBars /></Link>
<div className={`sidebar-overlay ${isOpen ? 'active' : ''}`} onClick={ToggleSidebar}></div>
</div>
<main>
<Outlet />
</main>
</div>
)
}
export default User
and this is my App.js
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Home />} >
<Route index element={<About />} />
<Route path="about" element={<About />} />
<Route path="signup" element={<Signup />} />
<Route path="login" element={<Login />} />
<Route path="guestuser" element={<GuestUser />} />
<Route path="User" element={<User />}>
<Route index element={<UserDefault />} />
<Route path="anesthesiatheory" element={<AnesthesiaTheory />} />
<Route path="anesquizmain01" element={<AnesMain01 />} />
<Route path="anesquiz01" element={<AnesQuiz01 />} />
<Route path="anesquizresult01" element={<AnesResult01 />} />
</Route>
</Route>
)
)
function App() {
return (
<div className="App">
<RouterProvider router={router} />
</div>
);
}
export default App;
What I want is that when I click on the toggle button, I want the sidebar to show without navigating me to default page. Kindly let me know what I am doing wrong. Looking forwards for your valuable suggestions.
here you are using
<Link className="btn" onClick={ToggleSidebar}><FaBars /></Link>
which is redirecting to default page,
use button
instead of <Link>
to solve this;
<button className="btn" onClick={ToggleSidebar}><FaBars /></button>
also clean your function for ToggleSidebar
from
const ToggleSidebar = () => {
!isOpen ? setIsopen(true) : setIsopen(false);
}
to
const ToggleSidebar = () => {
setIsopen(!isOpen)
}