Reactjs Get Input time value onchange

Viewed 1028

How do I get the value of an input type time in reactjs functional component. Here is an example I am getting.

<input type="time" onChange={(e) => console.log(e)} className="app-time" min="00:00" max="23:59" value={value} /> 

On console log event is printing but there is no target value on the console.How can I get the value in HH:mm format?

2 Answers

The value can be accessed via e.currentTarget.value.

Since it's a controlled component you'd want to call setValue in your change handler to make sure the input gets updated.

Edit hopeful-bush-57d1r

Just use event.target.value like in the code below. You can also set the step attribute to a value in seconds to control how granular the changes are. You can read more about time inputs on MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time

<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.15.8/babel.min.js"></script>

<div id="root"></div>

<script type="text/babel" data-type="module" data-presets="typescript,react">

const {useState} = React;

function Example (): React.ReactElement {
  const [value, setValue] = useState('00:00');

  return (
    <input
      type="time"
      onChange={ev => setValue(ev.target.value)}
      min="00:00"
      max="23:59"
      step="60"
      value={value}
    />
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>

Related