1

I want to display the date and time selected by the user from date-time picker on my UI . My code is as follows-

import React from 'react';
import '../App.css';
import Datetime from 'react-datetime';

class Datetimepicker extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
        moveaside: false,
        feed_items: [],
        newText: new Date(),
    };
    this.updateState = this.updateState.bind(this);
    this.showValuee = this.showValuee.bind(this);
}
updateState(e) {
    const text = e.value;
    console.log("text", text);
    this.setState({ newText: text });
    this.showValuee();
}
showValuee() {
    console.log(this.state.newText);
}
render() {
    console.log(this.props.value);
    return (
        <Datetime className={this.props.show ? 'rdt' : 'hide'} onChange={this.updateState} defaultValue={this.state.newText} />
    )
 }
}
export default Datetimepicker;

'text' shows undefined value.I am importing this 'Datetimepicker' component in my parent component and the Datetime picker I am using is this - (https://github.com/YouCanBookMe/react-datetime)

shreyaa
  • 93
  • 3
  • 14
  • In react, `setState` is asynchronous. If you want to log the value, you will have to use the callback for setState. https://stackoverflow.com/a/42038724/4374566 – Agney Jan 15 '18 at 09:38

1 Answers1

3

The documentation of react date time picker you have used uses onChange function programmatically and does not relay the change event back to the user. Instead the parameter inside onChange is the moment date object itself.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      datetime: ''
    }
    this.updateState = this.updateState.bind(this);
  }
  updateState(date) {
    // This function gives you the moment object of date selected. 
    console.log(date);
  }
  render() {
    return (
      <Datetime onChange={this.updateState}/>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<link rel="stylesheet" type="text/css" href="https://rawgit.com/arqex/react-datetime/master/css/react-datetime.css"/>

<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.js"></script>
<script src="https://rawgit.com/arqex/react-datetime/master/dist/react-datetime.js"></script>

Something else you should look up is how to use setState callback. Because setState is asynchronous, you cannot use a function to log the state value.

Agney
  • 18,522
  • 7
  • 57
  • 75