I am trying to do on change on datepicker, but the state doesn't update. I am using a state from props. So the date already exists. It shows expired dates. When I am doing the on change, it get stuck at the current date.
Something I am missing in the onChange handler?
constructor(props) {
super(props);
const {export} = this.props;
this.state = {showCalender: false};
this.date = export.expires;
this.handleChange = this.handleChange.bind(this);
}
static getDerivedStateFromProps(props, state) {
if (props.export.expires !== state.expires) {
return {
expires: props.export.expires
};
}
return null;
}
handleChange(date) {
this.setState({
expires: date
}, console.log(this.state.expires));
this.handleClick();
}
handleClick() {
this.setState({showCalender: !this.state.showCalender});
}
handleClear() {
this.setState({expires: ''});
}
render() {
const {expires, showCalender} = this.state;
const expiresDate = format(expires, 'MM/dd/yyyy');
return (
<div>
<FormGroup>
<FormControl
id="date"
value={expiresDate}
onChange={this.handleChange}
onClick={() => this.handleClick()}
title="set date"
aria-label="set date"
/>
<Button className="close-btn" onClick={() => this.handleClear()}>Clear</Button>
</FormGroup>
{ showCalender && (
<FormGroup>
<DatePicker
selected={expires}
onChange={this.handleChange}
inline
/>
</FormGroup>
)}
</div>
);
}
exportis a reserved keyword in ES6 so I highly encourage to change the name of the variable. If you are compiling this using ES6 it should throw an error