Search code examples
javascriptreactjsdatepickerreact-datepicker

Why doesn't this component show at all? React DatePicker


Here is the component:

import React, { Component } from 'react';
import DatePicker from 'react-datepicker';

class DatePickerCreater extends Component {
    constructor(props){
        super(props);
    }

    render() {
        return (
            <DatePicker
                disabled={this.props.answer.isDisabled}
                dateFormat="YYYY/MM/DD"
                selected={Date(this.props.answer.value)}
                onChange={(e) => this.props.blurHandler(e.target.value,this.props.answer)} 
            />
        );
    }
}

export default DatePickerCreater

when i try to render it, it shows nothing...

Very grateful for every answer!


Solution

  • The selected property takes a moment.js date, not a plain javascript date. You should get an error that says "date.clone is not a function ". You can fix that by using a moment date:

    import moment from 'moment';
    
    class DatePickerCreater extends Component {
        render() {
            return (
                <DatePicker
                    disabled={this.props.answer.isDisabled}
                    dateFormat="YYYY/MM/DD"
                    selected={moment(this.props.answer.value)}
                    onChange={(e) => this.props.blurHandler(e.target.value, this.props.answer)}
                />
            )
        }
    }
    

    Also you may have forgotten to import the react-datepicker css file. Without that the popup will not show correctly:

    import 'react-datepicker/dist/react-datepicker.css';
    

    EDIT

    Since they switched to using date-fns this answer is outdated. If you are using react-date-picker with a version >=2.0 you can no longer pass a moment.js instance. Instead use native Date objects and manipulate them using date-fns.

    For Reference:

    Up until version 1.8.0, this package was using Moment.js. Starting v2.0.0, we switched to using date-fns, which uses native Date objects, to reduce the size of the package. If you're switching from 1.8.0 to 2.0.0 or higher, please see the updated example above of check out the examples site for up to date examples.