Skip to content
Snippets Groups Projects
Commit ec01b659 authored by Bjarke Madsen's avatar Bjarke Madsen
Browse files

Automatically hide the sidebar when clicking outside

parent de0f429a
Branches
Tags
No related merge requests found
import React, { useState } from 'react'; import React, { useEffect, useState } from 'react';
// import { sidebarContext } from "../helpers/SidebarProvider"; // import { sidebarContext } from "../helpers/SidebarProvider";
import { AiOutlineClose, AiOutlinePlus } from 'react-icons/ai'; import { AiOutlineClose, AiOutlinePlus } from 'react-icons/ai';
...@@ -7,6 +7,8 @@ interface Props { ...@@ -7,6 +7,8 @@ interface Props {
children: React.ReactNode; children: React.ReactNode;
} }
// check if click outside of sidebar, then toggle it
const Sidebar: React.FC<Props> = ({ children }) => { const Sidebar: React.FC<Props> = ({ children }) => {
const [show, setShow] = useState<boolean>(false); const [show, setShow] = useState<boolean>(false);
...@@ -15,6 +17,21 @@ const Sidebar: React.FC<Props> = ({ children }) => { ...@@ -15,6 +17,21 @@ const Sidebar: React.FC<Props> = ({ children }) => {
setShow(!show); setShow(!show);
}; };
const clickOutside = (e) => {
// check if the click was inside the sidebar or the menu button
// if it was outside, close the sidebar
if (e.target.closest('#sidebar') || e.target.closest('.toggle-btn')) {
return;
}
setShow(false);
}
useEffect(() => {
document.addEventListener('click', clickOutside);
return () => {
document.removeEventListener('click', clickOutside);
}
});
return ( return (
<div className="sidebar-wrapper"> <div className="sidebar-wrapper">
<nav className={show ? '' : 'no-sidebar'} id="sidebar"> <nav className={show ? '' : 'no-sidebar'} id="sidebar">
... ...
......
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment