Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding div after a few seconds ReactJS

I'm trying to hide a div after a few seconds on ReactJS. Here is my code so far:

setTimeout(function() {
    $('#submitmsg').fadeOut('fast');
}, 3000);

<div id="submitmsg">
    {message && <span> Messaged received. I'll respond to your query ASAP!  </span> }
 </div>

I'm getting an error, saying that the "$" is undefined.

like image 224
hoseh Avatar asked Feb 07 '26 19:02

hoseh


1 Answers

$ is a sign for jquery
in react we would say

  document.getElementById('#submitmsg').fadeOut('fast');

also i would use a easier way by declaring a boolean is usestate

const Component = () =>{
  const [showElement,setShowElement] = React.useState(true)
  useEffect(()=>{
    setTimeout(function() {
      setShowElement(false)
         }, 3000);
       },
   [])
      
  return(
    <div>
       {showElement?<div>I'm here and i will be gone</div>:<></>} 
    </div>
  )
}

Update:

here i created a codesandbox example

and here is the whole code it is working fine when i try it as you can see in codesandbox above

import React, { useEffect } from "react";

const MyComponent = () => {
  const [showElement, setShowElement] = React.useState(true);
  useEffect(() => {
    setTimeout(function () {
      setShowElement(false);
    }, 10000);
  }, []);

  return (
    <div>
      <div>
        {showElement ? (
          <div
            style={{
              height: "100vh",
              background: "black",
              color: "white",
              fontSize: "30px",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              fontFamily: "roboto",
              opacity: showElement ? 1 : 0
            }}
          >
            I'm here and i will be gone
          </div>
        ) : (
          <div></div>
        )}{" "}
      </div>
    </div>
  );
};
export default MyComponent;

https://codesandbox.io/s/thirsty-rosalind-o9pds?file=/src/App.js

like image 86
Yahya Parvar Avatar answered Feb 09 '26 11:02

Yahya Parvar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!