简体   繁体   中英

How do i get value from a React date picker whenever i change the dates?

I am using a React library called react-date-picker, I want to get the date whenever I change it.

Here is the default code provided by the library to select the date from a dropdown

import React, { Component } from "react";
import DatePicker from "react-date-picker";

class MyApp extends Component {
  state = {
    date: new Date(),

  };

  onChange = date => {
    this.setState({ date });

  };

  render() {
    return (
      <div>
        <DatePicker onChange={this.onChange} value={this.state.date} />

      </div>
    );
  }
}

export default MyApp;

what I have tried to do:

import React, { Component } from "react";
import DatePicker from "react-date-picker";

class MyApp extends Component {
  state = {
    date: new Date(),
    new: ""
  };

  onChange = date => {
    this.setState({ date });
    console.log("changed");
    this.setState({ new: this.state.date });
  };

  render() {
    return (
      <div>
        <DatePicker onChange={this.onChange} value={this.state.date} />
        {console.log(this.state.new)}
      </div>
    );
  }
}

export default MyApp;

I am trying to store a value into a new state called "new" whenever someone changes the dates, which will trigger the onChange() and eventually store it into "new", then I am trying to do a console.log(this.state.new) for every time someone changes the dates.

I tried a few different approaches too, but failing to get it right. Any help would be really appreciated.

It sounds like you want to hold the date in state, and if a user updates the date to also store that in state. What you want to do is something like this:

onChange = date => {
  // update date and set new to null since first selection
  if ( !this.state.date && !this.state.new ){
   this.setState({ date, new: null })
  // update 'new' date but keep old date in state
  } else if (this.state.date && !this.state.new) {
   this.setState({ new: date})
  // move old new date to date and set newest selection to new
  } else { 
   this.setState({ date: this.state.new, new: date})
  }
};

As a side note, setState is asynchronous so it is not advised to call it twice in a row like you have it. If you want to make sure that the setState has finished updating the state before setting state again then you should use the second argument to setState which is a callback function like:

this.setState({ property: valye }, () => this.setState({ another_property: value })

instead of

onChange={this.onChange}

you can call the function on every change with an arrow function so that you can pass it a value of the event target, like this

onChange={e => this.onChange(e.target.value)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM