Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Datepicker( can't get value of input)

I am new in react. I need use react-datepicker

I want to get value of input, when I change date. If i click on 20th October 2017, i want put 20th October 2017 in my variable. But the main problem that I should work with component, not with input.

Before I just took value from state. Like this.state.value. But right now it is object(Moment) in state. And this object doesn't have value field.

There is my code:

export default class DatePicker extends Component {
constructor (props) {
    super(props);
    // this.props.date should looks like "29 November 2017 00:00"
    // second argument for moment() it is format of date, because RFC 2822 date time format
    this.state = {
        date: moment(this.props.value, 'LLL')
    };
}
handleChange = (date) => {
  // const valueOfInput = this.state.date  <--- I want string with date here
  console.log('this.state.date',this.state.date);
  this.setState({date: date});
};
render() {
    return <Form.Field>
              <Label>
                <Picker
                  selected={this.state.date}
                  onChange={this.handleChange}
                  dateFormat="LLL"
                  locale={this.props.language}
                />
              </Label>
          </Form.Field>

enter image description here

like image 306
SergeyB Avatar asked Nov 07 '17 14:11

SergeyB


3 Answers

Just use this:

handleChange = date => {
  const valueOfInput = date.format();
  ///...
};

Because this datepicker returns a moment.js object!

For more information, look into the moment.js docs here.

like image 110
Ihor Skliar Avatar answered Nov 07 '22 15:11

Ihor Skliar


Try this

<DatePicker 
   onChange={(value, e) => this.handleChange(value, e)}
   selected={this.state.inputValue} otherProps={here} 
/>

// you can access the value field in handleChange by e.target.value

handleChange(value, e) {
    console.log(value); // this will be a moment date object
    console.log(e.target.value); // this will be a string value in datepicker input field
}
like image 21
Karthik Avatar answered Nov 07 '22 15:11

Karthik


This solved for me by using the following:

handleDateChange = date => {
let selectedDateFromCalender = date.toUTCString();
this.setState({
      actualStartDate: selectedDateFromCalender,
  });}

<DatePicker
selected={this.state.startDate}
onChange={this.handleDateChange}/>

You can use the following methods as well, choose according to your requirement:

toISOString: "2020-10-05T09:10:38.000Z"

toJSON: "2020-10-06T09:09:16.000Z"

toUTCString: "Thu, 08 Oct 2020 09:11:24 GMT"

like image 40
debasish sahoo Avatar answered Nov 07 '22 15:11

debasish sahoo