ilse2005
ilse2005

Reputation: 11439

react-datepicker with no initial value

I started using the react-datepicker component. https://github.com/Hacker0x01/react-datepicker

I got the example running and now I want to adapt it that there is no initial value. The example code is the following:

 <script type="text/javascript">
 var container = document.querySelector('#datepicker-container');
 var exampleComponent = React.createClass({
    displayName: 'exampleComponent',
    getInitialState: function() {
      return {
         start_date: moment(),
      };
    },
    handleStartDateChange: function(date) {
       this.setState({
          start_date: date
       });
    },
   render: function() {
      return React.DOM.div({}, [
         DatePicker({
         key: 'example1',
         selected: this.state.start_date,
         onChange: this.handleStartDateChange
      }),

      ]);
   }
})
React.renderComponent(exampleComponent(), container);
</script>

I tried to use selected: none or even leave selected out but then I get the following error:

 TypeError: newProps.date is null
     value: newProps.date.format(this.props.dateFormat)

I also looked into the source code, but didn't find any possibility to start with an empty date. Thanks in advance for your help!

Upvotes: 5

Views: 21745

Answers (2)

Stefan de Clerk
Stefan de Clerk

Reputation: 21

Note: I'm using react-datepicker version 4.10

Setting start_date or selected to null didn't work for me, instead I simply changed the value for selected to "", as in selected={""}. That worked for me.

Upvotes: 0

Moaaz
Moaaz

Reputation: 156

You should be able to achieve what you want by setting start_date: null in your getInitialState,

Alternatively, if you use example 3 from react-datepicker, you can define a function like this:

handleResetDate: function() {
    this.setState({
        new_date: null
    });
},

, and call it whenever you want the date to reset.
Hope this helps!

Upvotes: 14

Related Questions