user2426823
user2426823

Reputation:

ReactJS + Material-UI: How to set current date as default value using Material-UI's <DatePicker>?

Currently I'm using ReactJS + Material-UI's <DatePicker> (http://www.material-ui.com/#/components/date-picker), and would like to have today's current date set as the default/initial value for the <DatePicker>. How can I go about doing so?

Current set up:

<DatePicker
  autoOk={true}
  hintText="Select Date"
  value={inputs.dateValue}
  onChange={this.handleDatechange}
/>

Upvotes: 9

Views: 46475

Answers (4)

Wowo Ot
Wowo Ot

Reputation: 1529

you can set it like that

import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import dayjs from 'dayjs';

. 
.
.

<LocalizationProvider dateAdapter={AdapterDayjs} >
    <DatePicker defaultValue={dayjs(new Date())} />

</LocalizationProvider>

Upvotes: 5

Serhii Onishchenko
Serhii Onishchenko

Reputation: 1141

In case using Redux-Form, like me, you can set the default in this way

In container set initialValues:

export default reduxForm({
    form: 'DateForm', 
    initialValues: { use_end_date: new Date() }
})(DateFormComponent);

For Field in component:

<Field
  name="use_end_date"
  component={ReduxMaterialDatePicker}
  margin="none"
/>

Upvotes: 1

Jatin Bansal
Jatin Bansal

Reputation: 181

Yoy can do something like this

this.state={
    date : new Date()
}

handleDatechange(event,date){
    this.setState({date: date})
}

<DatePicker
  autoOk={true}
  hintText="Select Date"
  value={this.state.date}
  onChange={this.handleDatechange}
/>

Upvotes: 9

Alex Young
Alex Young

Reputation: 4039

DatePickers default behaviour is to start on today's date. The only reason this wouldn't be the case is if you pass in either a defaultDate prop, or a value prop with a different date.

In your case you are passing value as inputs.dateValue, so this will be the initial value. You just need to ensure that the value of inputs.dateValue is set to today's date, for example,

inputs.dateValue = new Date();

Upvotes: 2

Related Questions