r/reactjs•
Pizdetss

component will not unmount

I have child component (sticky banner) that appears when the user scrolls down the page and disappears when they scroll back up. The parent component is panel and the problem I get is when I move onto the next panel the sticky component doesn't un mount. The scroll event listener just keeps listening for scroll. Is there anyway to trigger compontentwillunmount?

    import React 		from 'react';
    import classNames 	from 'classnames';
    import Scroll 		from 'react-scroll';

let scrollPos = null;

class Sticky extends React.Component {

constructor(props) {
	super(props);

	this.state = {
		show: false
	}
}

componentDidMount() {
	if(this.state.show === false) {
		var Events = Scroll.Events;
		var that = this;
		Events.scrollEvent.register('end', function(to, element) {
	      scrollPos = $(window).scrollTop();

	      window.addEventListener("scroll", that.handleScroll.bind(that));
	    });
	}
}

componentWillUnmount() {
	console.log('UNMOUNT')
	window.removeEventListener('scroll', this.handleScroll);
}

handleScroll() {

	if($(window).scrollTop() - scrollPos > 200) {
		this.setState({show: true});
	} else {
		this.setState({show: false});
		return;
	}
}

render() {

	let showSticky = false;

	if (this.state.show) {
		showSticky = true;
	}

	var stickyClasses = {
		'is-shown' : showSticky
	};

	return(
		<div className={classNames('sticky', stickyClasses)}>
			<h4 className="h5">Heading</h4>
			<button type="button" className="button">
					 Button
			</button>
		</div>
	);
}
}

Sticky.defaultProps = {};
Sticky.propTypes = {};
export default Sticky;

Posted Apr 15, 2016, 1:11 AM UTC · edited

56
Loading comments…