"Enhance your user experience with React-datepicker's seamless time selection

Is there a way to customize the react date picker to include seconds as well? I have looked through the documentation but couldn't find an option for selecting seconds. Any help or example would be appreciated, you can check out the input Time section (look for input Time)

I attempted to change the date format using dateFormat="MM/dd/yyyy h:mm:ss aa" but it didn't work.

() => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      timeInputLabel="Time:"
      dateFormat="MM/dd/yyyy h:mm aa"
      showTimeInput
    />
  );
};

I managed to display seconds by implementing a custom time input which is working fine. However, when used inside a MaterialUi Dialog, the entire dialog closes after selecting a time.

() => {
  const [startDate, setStartDate] = useState(new Date());
  const ExampleCustomTimeInput = ({ value, onChange }) => (
    <input
      type="time"
      step="1"
      value={value}
      onChange={e => onChange(e.target.value)}
      style={{ border: "solid 1px pink" }}
    />
  );
  return (
    <DatePicker
      selected={startDate}
      onChange={date => setStartDate(date)}
      showTimeInput
      customTimeInput={<ExampleCustomTimeInput />}
    />
  );
};

Answer №1

If you want to implement a custom time input with your own onChange function, you can make use of the customTimeInput property:

customTimeInput={
        <CustomTimePicker
          handleTimeChange={this.updateTime}
        />
      }

Below is the CustomTimePicker component for reference:

const CustomTimePicker = ({ currentTime, handleTimeChange }) => {
  const value = (currentTime instanceof Date && !isNaN(currentTime))
    ? currentTime.toLocaleTimeString('en-US')
    : '';

  return (
    <input
      className="time-input"
      type="time"
      step="1"
      value={value}
      onChange={(event) => handleTimeChange(currentTime, event.target.value)}
    />
  );
};

Here is an example implementation of the callback function:

updateTime = (currentTime, selectedTime) => {
  const [hours, minutes, seconds] = selectedTime.split(':');
  const newTime = (currentTime instanceof Date && !isNaN(currentTime)) ? currentTime : new Date();
  newTime.setHours(Number(hours) || 0, Number(minutes) || 0, Number(seconds) || 0);
  this.handleTimeUpdate(newTime);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with implementing a conditional template component within an AngularJS directive

As a Java/Python developer, I found myself working on an AngularJS project recently. While most concepts were easy to grasp, some of the syntax and functionality still elude me. The code I have handles login/logout functionality. If the user is logged in ...

The Discord Bot is displaying an error message labeled as "DiscordAPIError[50035]"

Here is the code in my ticket_system.js file: const { Client, MessageEmbed, MessageActionRow, MessageButton, Modal, TextInputComponent, } = require("discord.js"); const settings = require("./settings"); ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

What is the reason for not being able to locate the controller of the necessary directive within AngularJS?

A couple of angularjs directives were written, with one being nested inside the other. Here are the scripts for the directives: module.directive('foo', [ '$log', function($log) { return { restrict: 'E', r ...

Syntax Error in Node.js for MongoDB: Unexpected token or invalid symbol

I'm having trouble figuring out what's going on. Node v16.4.2, NPM v7.18.1 const mongoose = require("mongoose"); // const dotenv = require('dotenv') require('dotenv').config({path:'variables.env'}); mongoo ...

Javascript Encapsulation example

Could someone help me with this function query: var MyObject3 = function (a, b) { var obj = { myA : a, myB : b } ; obj.foo = function () { return obj.myA + obj.myB ; } ; obj.bar = function (c) { return obj.myA + c ; } ; return obj ; } ; I und ...

How can we ensure that the element being hovered over is brought to the forefront and placed in the center?

I have been tasked with replicating this specific object for a project. The creation process is going smoothly, but now the requirement is to make it stop when the user hovers over it. Implementing this hover functionality is not a problem as CSS provides ...

Achieving the Menu Hover Effect - step by step guide to recreating this stylish effect

I recently came across a stunning hover effect on the main menu of a website (red rectangles above menu). It's quite impressive! I found it here: Now, I want to incorporate this same effect into my own website. Unfortunately, there doesn't seem ...

The command npm install -g . fails to copy the package

The guidelines from npm's developer documentation suggest ensuring that your package can be installed globally before publishing by executing the command npm install -g .. I am currently working on developing an ES6 Command Line Interface (CLI) packag ...

Using `getJson` to parse the tree structure

I am currently working with a JSON file that contains order data. The structure of the JSON file is as follows: { "orders": [ {"name": "Peter", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64140110011624050b0 ...

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...

Changing state property upon clicking child element in React is not feasible

I am interested in changing the text color upon clicking it using a function triggered in a child element that affects the parent's state. This is because a specific property of the parent determines whether the text should be one color or another. W ...

Avoid triggering the pointerenter event when touching and subsequently moving into an element

I am currently working on a React application where I want to enable a user to touch one element and then move to an adjacent element while keeping the touch continuous. The issue I am facing is that the pointerover and pointerenter events only trigger whe ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

Sync HTML Videos

Issue: I am currently developing a 3 column layout where certain columns need to remain sticky at the top of the viewport. In one section, I want to use the same video as a background for all 3 columns, with the specific effect of having the middle column ...

What is the best way to update a prop value using a different function?

I have a single component in my NextJs application and I am trying to modify the child prop (referred to as type) of the child component when the <input> element is empty. However, I am facing issues with this task. Can someone please assist me? Tha ...

React component allowing for the reuse of avatars

As a novice in React, I've encountered a challenge. My goal is to develop a simple reusable component using MUI. Specifically, I aim to create an avatar component that can be easily customized with different images when called upon. I want the flexibi ...

Deleting empty tags in an HTML h1 element with JavaScript

Is there a way to use JavaScript to remove empty h1 tags only? <h1>Hello World!</h1> <p>Lorem ipsum dolor sit amet</p> <h1></h1> <p>consectetur adipiscing elit.</p> <h1></h1> <p>Sed do ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Associate information from a modal to a knockout model

I am attempting to utilize a Twitter Bootstrap modal that opens a window containing an editable text area. Upon saving, the relevant data should be saved. The current code I have is as follows: HTML: <table class="display table table-striped"> ...