vcc-ui
Version:
VCC UI is a collection of React UI Components that can be used for developing front-end applications at Volvo Car Corporation.
120 lines (104 loc) • 2.37 kB
JavaScript
import React from "react";
import PropTypes from "prop-types";
import { withTheme } from "react-fela";
import { Block } from "../block";
import { getThemeStyle } from "../../get-theme-style";
const hideOnScrollOffsetTop = 80;
const navStyle = ({ theme, sticky, hideOnScroll, isVisible }) => ({
position: "relative",
zIndex: 10,
width: "100%",
background: theme.colors.white,
boxSizing: "border-box",
":before": {
content: "''",
display: "block",
background: theme.colors.grey7,
height: 1,
outline: "none",
position: "absolute",
left: 0,
right: 0,
zIndex: -1,
bottom: 0
},
extend: [
{
condition: sticky,
style: {
position: "fixed",
top: 0,
left: 0
}
},
{
condition: hideOnScroll,
style: {
transition: "transform 200ms ease-out"
}
},
{
condition: !isVisible,
style: {
transform: "translateY(-100%)"
}
}
]
});
class NavComponent extends React.Component {
constructor(props) {
super(props);
this.state = { isVisible: true };
this.toggleVisibility = this.toggleVisibility.bind(this);
}
componentDidMount() {
if (this.props.hideOnScroll) {
window.addEventListener("scroll", this.toggleVisibility);
}
}
componentWillUnmount() {
if (this.props.hideOnScroll) {
window.removeEventListener("scroll", this.toggleVisibility);
}
}
toggleVisibility() {
let { isVisible } = this.state;
window.scrollY > this.previousScrollY
? isVisible &&
window.scrollY > hideOnScrollOffsetTop &&
this.setState({ isVisible: false })
: !isVisible && this.setState({ isVisible: true });
this.previousScrollY = window.scrollY;
}
render() {
const { sticky, hideOnScroll, children, theme } = this.props;
const { isVisible } = this.state;
const styleProps = {
sticky,
hideOnScroll,
isVisible,
theme
};
return (
<Block
as="nav"
extend={[navStyle(styleProps), getThemeStyle("nav", theme, styleProps)]}
>
{children}
</Block>
);
}
}
NavComponent.propTypes = {
/** Automatically hide the sticky navigation if the user starts scrolling */
hideOnScroll: PropTypes.bool,
/** Make the navigation stick to the top of the viewport */
sticky: PropTypes.bool
};
NavComponent.defaultProps = {
hideOnScroll: false,
sticky: false
};
NavComponent.displayName = "Nav";
const Nav = withTheme(NavComponent);
export { Nav };