Home > OS >  Remove a message after a minute
Remove a message after a minute

Time:04-18

Using react js, I was tasked in school to add a “timer” to a message that will delete after a minute and I’m really struggling with it. Can someone please help me. Thank you

CodePudding user response:

const [message, setMessage] = useState("");
    
    const handleClick = () => {
        setMessage("Message set..!")
    }
    
    useEffect(() => {
      setTimeout(() => {
        setMessage("")
      }, 60000);
    }, [message])
    
    return (
      <div>
        <h2> {message} </h2>
        <button onClick={handleClick}>Click</button>
      </div>
    );

CodePudding user response:

You can use set timer in your function and use state. Such as

  const [show, setShow] = useState(false)
   
  const handleShow = () => {
    setShow(true)
    const timer = setTimeout(() => {
     setShow(false)
    }, 1000); 
  }

  Your JSX Code

    { 
       // If state is true message would be displayed
       show && <p>This message will display only for one second</p>
    }
    <button onClick={()=>handleShow ()}> Click For Show</button>

CodePudding user response:

const Example = () => {
    const [value, setValue] = useState();
    const [message, setMessage] = useState("");
    const input = useRef();

    const HandleMessageChange = (e) => {
        setValue(e.target.value)
    }

    const HandleSettingValue = () => {
        setMessage(input.current.value)
    }

    useEffect(() => {
        setTimeout(()=>{
            setMessage("")
        },60000)
    }, [message])

    return (
        <Fragment>
            <h2>{message}</h2>
            <input ref={input} value={value} onChange={HandleMessageChange}/>
            <button onClick={HandleSettingValue}>send</button>
        </Fragment>
    )

}
  • Related