My aim is to give the user to see the alert at starting of the my page without clicking any button.And after a while it should be disappear automatically i am trying this on reactjs so any body help me out to find which logic should i apply
CodePudding user response:
Are you using class components
or functional components
for rendering your React page?
What you're looking for is called life cycles
, i highly recomend you taking a look in ReactJS life cycle docs.
The life cycle method that executes or do something when the page is loaded has two usages:
If you're using class components
, there is a native method you can call inside your component called ComponentDidMount()
, his usage is available in docs here.
Now, if you're using functional components
, you need to take a look on useEffect
in React Hooks.
After that, you can take a look in setTimeout
native method from javascript
as observed.
Hope this helps too!
CodePudding user response:
You can refer this link: custom-modal-popup-component
Also just make the state of modal true at fist and add a setTimeout in useEffect and make it to false after a desired time.
CodePudding user response:
First render your alert component. Define a boolean state variable with initial value false.
then update that state variable with setTimeout.
import React, { useState, useEffect } from "react";
export const Alert = () => {
const [timeIsUp, setTimeIsUp] = useState(false);
useEffect(() => {
setTimeout(() => {
setTimeIsUp(true);
}, 5000);
}, []);
if (timeIsUp) {
return null;
}
return <div>your actual alert component content</div>;
};