When building web applications, working with date and time inputs is a common requirement. HTML5 provides a native input type datetime-local
, but managing its value can be tricky when dealing with JavaScript Date objects. In this blog, we'll create a reusable DateTimeField
component in React, which can be used seamlessly in any React-based framework like Next.js or Gatsby.
Component Requirements
Our DateTimeField
component should:
- Accept a JavaScript Date object or a string representing the date-time as
defaultValue
. - Accept a JavaScript Date object or a string representing the date-time as
value
. - Properly format the input value to match the
datetime-local
format (YYYY-MM-DDTHH:MM
).
Implementation
Let's dive into the implementation of our DateTimeField
component:
import React from 'react';
const DateTimeField = ({ defaultValue, value, ...rest }) => {
const formatLocalDateTime = (date) => {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
const hours = `${date.getHours()}`.padStart(2, '0');
const minutes = `${date.getMinutes()}`.padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
};
const formattedDefaultValue = defaultValue ? formatLocalDateTime(new Date(defaultValue)) : '';
const formattedValue = value ? formatLocalDateTime(new Date(value)) : undefined;
return (
<input
{...rest}
type="datetime-local"
className="border p-1 rounded"
value={formattedValue}
defaultValue={formattedDefaultValue}
/>
);
};
export default DateTimeField;
Usage Example
To use the DateTimeField
component in your React application, you can import and render it like so:
import React, { useState } from 'react';
import DateTimeField from './DateTimeField'; // Adjust the path as needed
const App = () => {
const [dateTime, setDateTime] = useState();
const handleChange = (e) => {
setDateTime(e.target.value);
};
return (
<div className="app">
<h1>React DateTimeField Component</h1>
<DateTimeField
value={dateTime}
onChange={handleChange}
className="custom-class"
defaultValue={new Date()}
/>
<p>Selected DateTime: {dateTime}</p>
</div>
);
};
export default App;
Explanation
-
formatLocalDateTime
function: This utility function formats a JavaScript Date object into a string that conforms to thedatetime-local
input type (YYYY-MM-DDTHH:MM
). -
formattedDefaultValue
andformattedValue
: These constants store the formatted values for thedefaultValue
andvalue
props respectively. If these props are provided, they are converted to the required format; otherwise, empty strings are used. -
<input>
element: The input element uses thetype="datetime-local"
attribute, and applies the formatted values appropriately. TheclassName
attribute is used to style the input with some basic border and padding.
Browser Compatibility
Before using the datetime-local
input type, it's important to check its browser support, as it is not supported by all browsers globally. You can check the support on Can I Use.
Comments
Loading...