Step Level Up
creating-datetimefield-component-reactnextjsgatsby
M
Mahadev Mandal

· min read

Creating a DateTimeField Component with Default 'Now' Value in React, Next.js, and Gatsby

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:

  1. Accept a JavaScript Date object or a string representing the date-time as defaultValue.
  2. Accept a JavaScript Date object or a string representing the date-time as value.
  3. 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 the datetime-local input type (YYYY-MM-DDTHH:MM).

  • formattedDefaultValue and formattedValue: These constants store the formatted values for the defaultValue and value 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 the type="datetime-local" attribute, and applies the formatted values appropriately. The className 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.

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 DateTimeField component that simplifies the handling of date and time inputs in your React, Next.js, or Gatsby applications. This component ensures that date-time values are formatted correctly for the datetime-local input type, making your forms more robust and user-friendly. Happy coding!

Comments

Loading...

Mahadev Mandal

Written by Mahadev Mandal

I am a web developer with expertise in HTML, CSS, Tailwind, React.js, Next.js, Gatsby, API integration, WordPress, Netlify functions, the MERN stack, fullstack development, and NestJS.