how to disable past time in input type =time in reactjs

Viewed 39

Is there a way to disable past time input using input type='time'

I want the time to be restricted past time for the current day.

1 Answers

Check this answer. Use this along with javascript to set max property dynamically.

something like below

setInterval(() => {
  const d = new Date();
  input_refernce.setAttribute('max', `${d.getHours()}:${d.getMinutes()}`);
}, 60*1000)

Updated code

.tsx file

import * as React from 'react';
import './style.css';

export default function App() {
  const [maxTime, setMaxTime] = React.useState(
    `${new Date().getHours()}:${new Date().getMinutes()}`
  );
  React.useEffect(() => {
    const intervalId = setInterval(() => {
      const d = new Date();
      setMaxTime(`${d.getHours()}:${d.getMinutes()}`);
    }, 1000);

    return () => clearInterval(intervalId);
  }, []);
  return (
    <div>
      <input type="time" max={maxTime} />
      <span></span>
    </div>
  );
}

.css file

input:invalid + span:after {
  content: ' ✖';
}

input:valid + span:after {
  content: ' ✓';
}
Related