15

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

SergeyB
  • 335
  • 1
  • 3
  • 10

8 Answers8

11

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.

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Ihor Skliar
  • 384
  • 2
  • 16
7

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
}
palerdot
  • 7,416
  • 5
  • 41
  • 47
Karthik
  • 65
  • 1
  • 4
1

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"

0

If you want to get the new value (once the user clicks on a new date from DatePicker) pass the event to the method.

class MyComponent extends React.Component {
  constructor(props) {
    this.state = {inputValue: moment(),} // this will set the initial date to "today", 
                                         // you could also put another prop.state value there
    this.handleChange = this.handleChange.bind(this);
  }
  }


  handleChange(value) {
    console.log(value); // this will be a moment date object
    // now you can put this value into state
    this.setState({inputValue: value});
  }

  render(){
    ...
    <DatePicker 
       onChange={(event) => this.handleChange(event)}
       selected={this.state.inputValue} otherProps={here} />
    ...
  }
};
dmayo
  • 640
  • 6
  • 16
0

The new version of react-datepicker library stopped using a moment.js object, so here is my solution if you want to get a formatted string representation of the date.

First import import format from "date-fns/format"; Then

    <DatePicker 
       onChange={(value)=>this.handleChange(format(value, "yyyy/MM/dd", { 
       awareOfUnicodeTokens: true }))}
       dateFormat="yyyy/MM/dd"
       selected={this.state.inputValue} otherProps={here} />
    ...
Sujal Patel
  • 2,444
  • 1
  • 19
  • 38
0

You can use the getTime() helper function on your date object to get the millisecond timestamp for that specific date, which is a JavaScript number data type. Useful for saving data in the backend of your application. For example Flask Peewee ORM requires a timestamp to be saved for the DateTimeField.

const [startDate, setStartDate] = useState(new Date())

<DatePicker
  onSelect( date => {
    setStartDate(getTime(date))
  }
/>

source: https://date-fns.org/v2.0.0-alpha.7/docs/getTime

Combine it with an effect to set the default state value to a timestamp on page load:

useEffect(() => {
    setStartDate(getTime(startDate))
  }, [])

Otherwise for your UI, you can use the format() helper function to get the string value of the given object, with any given format:

<h1>{format(startDate, "MMMM d, yyyy h:mm aa")}</h1>

source: https://date-fns.org/v2.0.0-alpha.7/docs/format

0

I have same problem, and I solved it by using the below solution. Please try it:

<p>{this.state.date.toLocaleDateString()}</p>
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
PhongVH
  • 51
  • 8
0
<input id="tdate" type="date" name="todate" onchange="getToDate(event);">

function getToDate(e){
 const tdate = e.target.value;

//alert(tdate);
//console.log(tdate);
//return tdate;
};

here i am trying to access "tdate" variable outside the function.