Handling date inputs is a common requirement in web applications. HTML5 provides a native input type date
, but managing its value with JavaScript Date objects can be tricky. In this blog, we'll create a reusable DateField
component in React, which can be used seamlessly in any React-based framework like Next.js or Gatsby.
Component Requirements
Our DateField
component should:
- Accept a JavaScript Date object or a string representing the date as
defaultValue
. - Accept a JavaScript Date object or a string representing the date as
value
. - Properly format the input value to match the
date
format (YYYY-MM-DD
).
Implementation
Let's dive into the implementation of our DateField
component:
import React from 'react';
const DateField = ({ defaultValue, value, ...rest }) => {
const formatDate = (date) => {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
return `${year}-${month}-${day}`;
};
const formattedDefaultValue = defaultValue ? formatDate(new Date(defaultValue)) : '';
const formattedValue = value ? formatDate(new Date(value)) : undefined;
return (
<input
{...rest}
type="date"
className="border p-1 rounded"
value={formattedValue}
defaultValue={formattedDefaultValue}
/>
);
};
export default DateField;
Usage Example
To use the DateField
component in your React application, you can import and render it like so:
import React, { useState } from 'react';
import DateField from './DateField'; // Adjust the path as needed
const App = () => {
const [date, setDate] = useState();
const handleChange = (e) => {
setDate(e.target.value);
};
return (
<div className="app">
<h1>React DateField Component</h1>
<DateField
value={date}
onChange={handleChange}
defaultValue={new Date()}
className="custom-class"
/>
<p>Selected Date: {date}</p>
</div>
);
};
export default App;
Explanation
-
formatDate
function: This utility function formats a JavaScript Date object into a string that conforms to thedate
input type (YYYY-MM-DD
). -
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="date"
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 date
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.
Styling
The component includes some basic styling using Tailwind CSS classes. You can customize it further or use a different styling approach as per your project requirements.
.border {
border: 1px solid #ccc;
}
.p-1 {
padding: 0.25rem;
}
.rounded {
border-radius: 0.25rem;
}
Conclusion
By following this guide, you have created a reusable DateField
component that simplifies the handling of date inputs in your React, Next.js, or Gatsby applications. This component ensures that date values are formatted correctly for the date
input type, making your forms more robust and user-friendly. Happy coding!
Comments
Loading...