- Published on
How to build a custom Sidebar Component in React
- Authors
- Name
- Ashik Nesin
- @AshikNesin
import React from 'react';
import ReactDOM from 'react-dom';
import { IndexLink, Link } from 'react-router';
import './Sidebar.scss';
import classNames from 'classnames';
class Sidebar extends React.Component {
constructor(props) {
super(props);
this.state = {
showMenu: false,
};
this.toggleMenu = this.toggleMenu.bind(this);
}
componentDidMount() {
document.addEventListener(
'click',
this.handleClickOutside.bind(this),
true
);
}
componentWillUnmount() {
document.removeEventListener(
'click',
this.handleClickOutside.bind(this),
true
);
}
toggleMenu() {
this.setState({ showMenu: !this.state.showMenu });
}
handleClickOutside(event) {
const domNode = ReactDOM.findDOMNode(this);
if (!domNode || !domNode.contains(event.target)) {
this.setState({
showMenu: false,
});
}
}
render() {
const showMenu = this.state.showMenu;
const sidebarClass = classNames({
sidebar: true,
'sidebar-menu-expanded': showMenu,
'sidebar-menu-collapsed': !showMenu,
});
const elementsClass = classNames({
'expanded-element': true,
'is-hidden': !showMenu,
});
return (
<nav className={sidebarClass}>
<img className="menuIcon" src={menuIcon} onClick={this.toggleMenu} />
<ul>
<li>
<Link className="expandable" to="/setting" title="Setting">
<img src={'https://png.icons8.com/setting/ffffff'} alt="" />
<span className={elementsClass}>Setting</span>
</Link>
</li>
</ul>
</nav>
);
}
}
export default Sidebar;
// Sidebar.scss
.menuIcon {
margin-top: 70px;
cursor: pointer;
}
nav.sidebar-menu-collapsed {
width: 70px;
}
nav.sidebar-menu-expanded {
width: 211px;
z-index: 1;
}
nav.sidebar {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
background: none repeat scroll 0 0 #000000;
color: white;
padding: 20px 10px;
}
nav.sidebar a#justify-icon {
outline: 0;
color: white;
font-size: 24px;
font-style: normal;
}
nav.sidebar ul {
margin: 0;
padding: 0;
// margin-top: 60px;
}
nav.sidebar ul li {
margin: 0;
padding: 0;
margin-top: 20px;
list-style-type: none;
}
nav.sidebar ul li a.expandable {
outline: 0;
color: white;
text-decoration: none;
font-size: 20px;
}
nav.sidebar ul li a.expandable:hover {
color: #bbbbbb;
}
nav.sidebar ul li a.expandable span.expanded-element {
color: #fff;
margin-left: 12px;
// display: none;
font-size: 16px;
position: relative;
bottom: 2px;
}
nav.sidebar ul li.active {
background: none repeat scroll 0 0 black;
border-radius: 4px;
text-align: center;
margin-left: -4px;
padding: 4px;
}
nav.sidebar ul li.active a.expandable {
color: white !important;
}
nav.sidebar ul li.active a.expandable:hover {
color: white !important;
}