How to make a component appear after the page has loaded?
Clash Royale CLAN TAG#URR8PPP
How to make a component appear after the page has loaded?
I have a Newsletter component that I want to show when the page has loaded as a popup. Right now it get's displayed after a click on a button, how can I do that? I know there is react-popup but I don't want to do it that way, here is my component:
import React from 'react';
import './newsletter.css';
class Newsletter extends React.Component
constructor(props)
super(props);
this.state =
modalOpened: false
;
this.modalToggle = this.modalToggle.bind(this);
modalToggle()
this.setState( modalOpened: !this.state.modalOpened );
render()
const coverClass = this.state.modalOpened ? 'modal-cover modal-cover-active' : 'modal-cover';
const containerClass = this.state.modalOpened ? 'modal-container modal-container-active' : 'modal-container';
return (
<div>
<button className="btn btn-primary" onClick=this.modalToggle>
Sign up for our Newsletter!
</button>
<div className=containerClass>
<div className="modal-header" />
<h1> Want more offers? Sign Up! </h1>
<div className="modal-body">
<form action="#" className="form">
<input type="email" className="input" />
<input className="newsletter-submit" type="submit" value="Submit" />
</form>
</div>
<div className="modal-footer" />
</div>
<div className=coverClass onClick=this.modalToggle />
</div>
);
export default Newsletter;
I tried putting it in a ComponentWillMount cycle but it did not work, how can I do that?
1 Answer
1
If you want the modal to show directly when the component is created, you can default modalOpened
to true
instead of false
in the constructor.
modalOpened
true
false
constructor(props)
super(props);
this.state =
modalOpened: true
;
this.modalToggle = this.modalToggle.bind(this);
If you want to show the modal after a certain amount of time, you could use a setTimeout
that uses setState
after a certain amount of time has elapsed.
setTimeout
setState
componentDidMount()
setTimeout(() => this.setState( modalOpened: true ), 3000);
Thanks, I was also thinking about doing it with a timeout, for example load the modal after a minute or so, I tried modalOpened: setTimeout(false, 3000) but it didn't work how should it be done?
– user10182767
Aug 6 at 7:52
@RogerCrowley I updated the answer
– Tholle
Aug 6 at 10:26
It worked, thanks!
– user10182767
Aug 7 at 7:28
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Did my answer work for you?
– Tholle
Aug 7 at 0:17