Search code examples
reactjshidetransition

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.


Solution

  • $ 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