RamAlx
RamAlx

Reputation: 7344

Default Value in react-datepicker

i'm using react-datepicker module in my react-redux app and i made it compatible with redux form like this:

const MyDatePicker = props => (
  <div>
    <DatePicker
      {...props.input}
      dateFormat="DD-MM-YYYY"
      selected={props.input.value
        ? moment(props.input.value, 'DD-MM-YYYY')
        : null}
      placeholderText={props.placeholder}
      disabled={props.disabled}
    />
    {
      props.meta.touched && props.meta.error &&
      <span className="error">
        { props.intl.formatMessage({ id: props.meta.error }) }
      </span>
    }
  </div>
);

The problem is that i dont know how to add a default value in my module. This default value must be today. Any ideas of how to handle this?

Upvotes: 3

Views: 71824

Answers (3)

Ved
Ved

Reputation: 12113

change:

 selected={props.input.value
        ? moment(props.input.value, 'DD-MM-YYYY')
        : null}

t0

 selected={props.input.value ? moment(props.input.value, 'DD-MM-YYYY') : moment()}


const MyDatePicker = props => (
  <div>
    <DatePicker
      {...props.input}
      dateFormat="DD-MM-YYYY"
  selected={props.input.value ? moment(props.input.value, 'DD-MM-YYYY') : moment()}
      placeholderText={props.placeholder}
      disabled={props.disabled}
    />
    {
      props.meta.touched && props.meta.error &&
      <span className="error">
        { props.intl.formatMessage({ id: props.meta.error }) }
      </span>
    }
  </div>
);

Upvotes: 7

Dennis
Dennis

Reputation: 714

You can specify initial form values in the mapStateToProps phase:

const mapStateToProps = state => {
  return {
    initialValues: {
      date: moment()
    } // Use the `initialValues` property to set your initial data
  };
}

This is also explained here: http://redux-form.com/6.6.3/examples/initializeFromState/

Upvotes: 2

Shubham Khatri
Shubham Khatri

Reputation: 282040

You should use moment(dt).format() to format the date

const MyDatePicker = props => {
  var date = new Date();
  var todayDate = moment(date).format('DD-MM-YYYY');
  return (
  <div>
    <DatePicker
      {...props.input}
      dateFormat="DD-MM-YYYY"
      selected={props.input.value
        ? moment(props.input.value).format('DD-MM-YYYY')
        : todayDate}
      placeholderText={props.placeholder}
      disabled={props.disabled}
    />
    {
      props.meta.touched && props.meta.error &&
      <span className="error">
        { props.intl.formatMessage({ id: props.meta.error }) }
      </span>
    }
  </div>
  );
}

Upvotes: 3

Related Questions