Skip to content

Instantly share code, notes, and snippets.

@Saifadin
Created August 29, 2018 17:22
Show Gist options
  • Save Saifadin/05ed98eb57a0d6d8be7b4defd0c982ad to your computer and use it in GitHub Desktop.
Save Saifadin/05ed98eb57a0d6d8be7b4defd0c982ad to your computer and use it in GitHub Desktop.
Example of a stateful component
class NavigationBar extends React.Component {
state = {
scroll: window.pageYOffset,
navContainer: null,
active: false,
};
componentDidMount() {
this.setState({
navContainer: document.getElementById('NavContainer').offsetTop,
active: 'description',
});
window.addEventListener('scroll', this.handleScrollEvent);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScrollEvent);
}
setActive = props => {
const { item, yValue } = props;
this.setState({
active: item,
});
window.scrollTo({
top: yValue - 67,
behavior: 'smooth',
});
};
handleScrollEvent = () => {
const { scroll, active, navContainer } = this.state;
const isFixed = scroll >= navContainer;
const yValues = [];
this.setState({
scroll: window.pageYOffset,
});
pageAnchors.map(item => {
const elId = document.getElementById(`${item}`);
yValues.push(elId.offsetTop - 72);
});
yValues.forEach((item, index) => {
if (scroll >= item && (index + 1 === yValues.length || scroll <= yValues[index + 1])) {
this.setState({
active: pageAnchors[index],
});
}
});
if (isFixed && window.innerWidth <= SIZE_TABLET) {
const activeEl = document.getElementById(`nav${active}`);
if (activeEl.offsetLeft > window.innerWidth) {
activeEl.scrollIntoView({ behavior: 'instant', inline: 'end' });
} else if (activeEl.offsetLeft < window.innerWidth) {
activeEl.scrollIntoView({ behavior: 'instant', inline: 'end' });
}
}
};
toTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
};
render() {
const { scroll, navContainer } = this.state;
const isFixed = scroll >= navContainer;
return (
<NavContainer id="NavContainer">
<NavWrapper isFixed={isFixed}>
{pageAnchors.map(item => {
const elId = document.getElementById(`${item}`);
const yValue = elId && elId.offsetTop;
return (
<MenuItem
key={uniqId()}
name={item}
id={`nav${item}`}
isActive={this.state.active === item}
setActive={() => {
this.setActive({ item, yValue });
}}
/>
);
})}
</NavWrapper>
<ToTop onClick={this.toTop} isFixed={isFixed}>
<Icon name="up" size="large" />
</ToTop>
</NavContainer>
);
}
}
const mapStateToProps = ({ i18n }) => {
return { locale: i18n.locale };
};
export default connect(mapStateToProps)(NavigationBar);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment