3

I am trying to use react-datepicker package to create my own date picker component, i have modified some of the basic stuff to have a control on it and it all seems to work but my onChange doesn't change the date on the view... i can see the log the onChange does fire but nothing happens when i choose a new date on screen. Am fairly new and trying to understand what i did wrong.

Here is my DateTimePicker.tsx

import type { FC } from 'react';
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

import './DateTimePicker.css';

export interface Props {
    /**
     * Determines format of date to be displayed
     * tag i.e. format=dd/MM/yyyy => 24/12/2020
     */
    format?: 'dd/MM/yyyy' | 'mm/dd/yyyy' | 'yyyy/MM/dd' | 'yyyy/dd/MM';
    /** on change method updates the date input field with selected date */
    onChange(date: Date | null, event: React.SyntheticEvent<any, Event> | undefined): void;
    /**  Determine the type of dropdown of year and month selecter */
    mode?: 'select' | 'scroll';
    /** Placeholder for no date is selected */
    placeholder?: string;
}
/**
 * Component that serves as an datepicker input field to let the user select Date
 *
 * @return DateTimePicker component
 */
export const DateTimePicker: FC<Props> = ({
    format = 'dd/MM/yyyy',
    mode = 'select',
    placeholder = 'Click to add a date',
    onChange,
}) => {
    return (
        <DatePicker
            className="apollo-component-library-date-picker-component"
            placeholderText={placeholder}
            dateFormat={format}
            onChange={onChange}
            dropdownMode={mode}
            showMonthDropdown
            showYearDropdown
            adjustDateOnChange
        />
    );
};
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
newbie
  • 103
  • 2
  • 7
  • Try this `onChange={(date) => onChange(date)}` – Keaton Benning Feb 14 '22 at 20:45
  • nope did'nt worked @KeatonBenning – newbie Feb 14 '22 at 21:18
  • Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content ([under the CC BY-SA 4.0 license](https://stackoverflow.com/help/licensing)). By SE policy, any vandalism will be reverted. – Luca Kiebel Feb 15 '22 at 16:12

1 Answers1

1

react-datepicker takes a selected prop that keeps track of the currently selected date. You'll need to manage it in state and provide it to the component:

const Example = () => {
  const [startDate, setStartDate] = useState(new Date());

  return (
    <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />
  );
};
Keith Brewster
  • 3,302
  • 2
  • 21
  • 28