reactjsreact-datetime

How to get defaulValue of YouCanBookMe/react-datetime component?


I am using react-dateTime version"react-datetime": "^2.8.10", I am using default Value. When i click on edit button i get the default value of react-dateTime. but when i update data and i am not changing the datetime.I want that that defaultValue.and when i update data with out changing date-time.i get current date-time.Then in that case how to get that defaultValue. How to get defaultValue of react-DateTime?

renderForm:function(){
    var yesterday = Datetime.moment().subtract( 1, 'day' );
        var valid = function( current ){
        return current.isAfter( yesterday );
        };
        var dateTimeStart=moment(this.props.todo_start_at);
        var dateTimeEnd=moment(this.props.todo_end_at);
        console.log("dateTimeStart ",dateTimeStart)
        console.log("dateTimeEnd ",dateTimeEnd)
    return( 
        <form onSubmit={this.handleUpdate}>
            <input type="text"ref={(value)=>{
                this.input=value
            }}defaultValue={this.props.todo_text}/>
            <div className="column medium-4">
                When To Start
                <Datetime input={ true } isValidDate={ valid } dateFormat="YYYY-MM-DD"  defaultValue= { dateTimeStart }onChange={ this.handleDateTimeStart } />
            </div>
            <div className="column medium-4">
                When To End
                <Datetime input={ true } isValidDate={ valid } dateFormat="YYYY-MM-DD" defaultValue= { dateTimeEnd }onChange={ this.handleDateTimeEnd }  />
            </div>
                <br/>
            <button type="button" className="button" onClick={this.handleUpdate}>Update</button>
        </form>
        )
},

handleupdate

handleUpdate:function(event){
        event.preventDefault();
        //console.log(this.dateTimeStart.value);
        var startDate=this.state.dateTimeStart.value;
        console.log(startDate);
        var todoStartDate= moment(startDate).format('YYYY-MM-DD HH:mm');
        var dueDate=this.state.dateTimeEnd.value;
        var todoEndDate=moment(dueDate).format('YYYY-MM-DD HH:mm');
        console.log("handle update",todoEndDate)
        this.props.editTask(this.props.todo_id,this.input.value,todoStartDate,todoEndDate);
        this.toggleState();
    },

Solution

  • Reason is, you are initialising the state value by "" (blank value), and updating that when user changes the date, otherwise not. So in that case when user is not updating the value this.state.dateTimeStart.value will be undefined, previous value (default value) will be present in this.props.todo_start_at.

    You need to take that default value when user is not doing any change.

    Use these line inside handleUpdate method:

    var startDate = this.state.dateTimeStart.value || this.props.todo_start_at;
    var dueDate = this.state.dateTimeEnd.value || this.props.todo_end_at;