Home > Net >  react datepicker default value
react datepicker default value

Time:12-23

I am using react datepicker and I don't want to set the default value, but still it is taking value.

  <DatePicker
                    dateFormat="dd/MM/yyyy"
                    minDate={subDays(new Date(), 0)}
                    wrapperClassName="date-picker"
                    selected={this.state.from_date}
                    onChange={(date: any) => {
                      this.setState({
                        from_date: date,
                      });
                    }}
                    customInput={<ExampleCustomInput />}
                    dayClassName={() => "example-datepicker-day-class"}
                    popperClassName="example-datepicker-class"
                    todayButton="TODAY"
                  />

CodePudding user response:

It looks like the selected prop in your DatePicker component is being set to this.state.from_date, which is likely causing the default value to be set. To avoid this, you can try setting the selected prop to null or some other value that you want to use as a placeholder until the user selects a date. For example:

<DatePicker
  dateFormat="dd/MM/yyyy"
  minDate={subDays(new Date(), 0)}
  wrapperClassName="date-picker"
  selected={this.state.from_date || null}  // use null as placeholder
  onChange={(date: any) => {
    this.setState({
      from_date: date,
    });
  }}
  customInput={<ExampleCustomInput />}
  dayClassName={() => "example-datepicker-day-class"}
  popperClassName="example-datepicker-class"
  todayButton="TODAY"
/>

CodePudding user response:

If you don't want to set the default value for a date picker in React, you can initialize the selected prop with an empty value, like this:

import DatePicker from 'react-datepicker';

const App = () => {
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);

  return (
    <DatePicker
      selected={selectedDate}
      onChange={date => setSelectedDate(date)}
    />
  );
}

This will initialize the date picker with no selected date, and the user will have to select a date manually. If the user hasn't selected a date, the input field will be empty.

Alternatively, you can also pass a null value to the selected prop to initialize the date picker with no selected date:

import DatePicker from 'react-datepicker';

const App = () => {
  return (
    <DatePicker
      selected={null}
      onChange={date => console.log(date)}
    />
  );
}
  • Related