You need to work with state, Like loading for first time would be null. On submit, it will be true/loading. Once loaded, need to be false.
Or you can create a component like Toast and based on data you can play.
function Toast({open, message, autoClose, type = "info", timeout = 2000}) {
const [status, setStatus] = useState(open);
useEffect(() => {
if(autoClose) {
setTimeout(() => {
setStatus(false);
}, timeout);
}
}, []);
return (
<div>
{status ? (
<span className={"message-sent" + " " +type}>
{message}
</span>
) : null}
</div>
)
}
See below example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<style>
.error {
background-color: red;
}
.info {
background-color: blue;
}
</style>
</head>
<body>
<div id="root">Test</div>
<script type="text/babel">
const { createElement, useState, useEffect, useRef } = React;
function Toast({open, message, autoClose, type = "info", timeout = 2000}) {
const [status, setStatus] = useState(open);
useEffect(() => {
if(autoClose) {
setTimeout(() => {
setStatus(false);
}, timeout);
}
}, []);
return (
<div>
{status ? (
<span className={"message-sent" + " " +type}>
{message}
</span>
) : null}
</div>
)
}
function Loader() {
const [status, setStatus] = useState(null);
useEffect(() => {
setTimeout(() => {
setStatus(false);
}, 2000);
}, [status]);
const onSubmit = () => {
setStatus(true);
};
return (
<div>
{status === true ? (
<span className="message-sent">
Your message has been sent. We will get back to you soon. Thank you
for contacting us!
</span>
) : null}
<button onClick={onSubmit}>Click here to see message</button>
</div>
);
}
ReactDOM.render(<div>
<Loader />
<Toast open message={"Auto close message"} autoClose type="error" />
<Toast open message={"info message"} autoClose timeout={4000}/>
</div>, document.getElementById("root"));
</script>
</body>
</html>
falseso that the condition rendernull.