Skip to content

Instantly share code, notes, and snippets.

@adrianmcli
Created December 15, 2017 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrianmcli/c323cf1f827371e11361bb2aa69a1e5e to your computer and use it in GitHub Desktop.
Save adrianmcli/c323cf1f827371e11361bb2aa69a1e5e to your computer and use it in GitHub Desktop.
Fixed topnav navbar example with responsive side menu.
import React from "react";
import styled from "styled-components";
const Container = styled.nav`
background: darkred;
/* make this a fixed navbar at the top, with fixed height */
position: fixed;
top: 0;
right: 0;
left: 0;
height: 64px;
/* add a nice shadow effect */
z-index: 1;
box-shadow:
0 10px 20px rgba(0,0,0,0.19),
0 6px 6px rgba(0,0,0,0.23);
/* center the inner container */
display: flex;
justify-content: center;
`;
const Content = styled.div`
background: red;
/* layout children horizontally */
display: flex;
justify-content: space-between;
/* as wide as it can be, but not too wide */
width: 100%;
max-width: 480px;
`;
const SideNav = styled.div`
background: yellow;
/* always show on mobile but can be tucked away;
fixed width and add transition */
display: block;
width: 300px;
transition: left 200ms ease-in-out;
/* set it on the side */
position: fixed;
top: 0;
bottom: 0;
left: ${p => (p.show ? `0` : `-100%`)};
/* hide on larger screens */
@media screen and (min-width: 600px) {
display: none;
}
`;
const Logo = styled.div``;
const TopNav = styled.div`
display: none;
/* show on larger screens */
@media screen and (min-width: 600px) {
display: block;
}
`;
const MobileMenuButton = styled.div`
display: block;
padding: 6px;
border: 2px solid white;
/* hide on larger screens */
@media screen and (min-width: 600px) {
display: none;
}
`;
export default class extends React.Component<{}, { showSideNav: boolean }> {
state = { showSideNav: false };
toggleSideNav = () => this.setState(p => ({ showSideNav: !p.showSideNav }));
render() {
return (
<Container>
<Content>
<Logo>LOGO</Logo>
<TopNav>Top Nav buttons for desktop here</TopNav>
<MobileMenuButton onClick={this.toggleSideNav}>
Open mobile menu
</MobileMenuButton>
</Content>
<SideNav show={this.state.showSideNav}>
SideNav here
<button onClick={this.toggleSideNav}>close</button>
</SideNav>
</Container>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment