After i set some div to show after scroll, the result is the div is not hidden when the page is open(or reload)
I have tried to have the - componentWillMount, and - componentDidMount for the lifecycle, but i got the same result
This is the code
constructor(props){
super(props);
this.state={
isHide:false,
};
this.hideBar = this.hideBar.bind(this)
}
hideBar(){
let {isHide} = this.state;
window.scrollY < 300 && this.prev ?
!isHide && this.setState({isHide:true})
:
isHide && this.setState({isHide:false})
this.prev = window.scrollY;
}
componentWillMount(){
window.addEventListener('scroll',this.hideBar);
}
componentWillUnmount(){
window.removeEventListener('scroll',this.hideBar);
}
render() {
let classHide=this.state.isHide?"newsletterhide":""
return (
<div className={classHide+"newsletter-container"}>
<div className="newsletter-details">
<h3 style={{margin:0, fontSize:"0.9em"}}>
Get latest updates in web technologies
</h3>
<p className="p-newsletter">
I write articles related to web technologies, such as design trends, development tools, UI/UX case studies and reviews, and more. Sign up to my newsletter to get them all.
</p>
</div>
<div className="newsletter-form">
<input
name="email"
type="email"
placeholder="Email address"
className="newsletter-input"
/>
<button className="newsletter-button">
Count me in!
</button>
</div>
</div>
);
}
Thanks for your help!, hope the other who need it find it useful.
As I understood, you want to show subscribe to newsletter box when user scrolls down in the page. Why don't you just write:
hideBar() {
this.setState({
isHidden: window.scrollY < 300
});
}
And setting isHidden
to true
at the beginning should solve your problem. If not, then call hideBar
method at componentDidMount
.
And also, I recommend that you show the newsletter box after user spend some time looking at the website; eg show it 15 seconds after he/she reads the article.
Assuming the problem is during reloads there being a page offset and your intension is to show the div then,
componentDidMount() {
if(window.pageYOffset) this.setState({ isHide: false, });
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.