Home > other >  How to listen for time change in React?
How to listen for time change in React?

Time:08-24

I have a button which I want to remain disabled unless in a certain time window. Is there any way to do this in react? I dont want to hard code it like

<button disabled={isCorrectTime()}>...

because if the user is already on the page, and the time changes to the correct time, the button will not get updated right? does anyone know of any solutions?

CodePudding user response:

You call setTimeout inside of the useEffect Hook . useEffect method runs when it first renders then setTimeout block runs after some seconds (these seconds passed into the second parameter of the setTimeout method) then you call the clearTimeout() to cancel a timer .

Example :

import React, {useEffect, useState} from 'react'

function App() {
  const [disabled, setdisabled] = useState(true)
  useEffect(() => {
    const timer = setTimeout(() => {
      setdisabled(false);
    }, 3000);
    return () => clearTimeout(timer);
  }, []);
  
  return (
    <div>
      <h1> hello </h1>
      <button disabled= {disabled} > click me </button>
    </div>
  )
}

export default App

CodePudding user response:

Is the time window a specific amount of time after a certain event? If so, you can use a timeout function to change a state variable that you can then use to control the disabled state of the button:

const [isDisabled, setIsDisabled] = useState(true)

setTimeout(() => {
  setIsDisabled(false);
}, 1000)
// set this time to whatever the desired length of time is
...
<button disabled={isDisabled} />

If this doesn't work, you might be able to use setInterval() to periodically check the current time, but I will need more information about what your goals are to know if that's the best way forward.

  • Related