'How do you re-render DatePicker with updated defaultValue?

I'm using DatePicker in the following scenario:

  1. Render the form that used DatePicker
  2. on componentDidMount, fetch form's saved information (if it was saved previously)
  3. set DatePicker's prop defaultValue from undefined to the fetched value

Seems pretty simple. But, since DatePicker's behaviour is to render defaultValue only on the first render, it obviously is empty when the value is fetched (second render).

The other two options i see:

  1. Have a controlled component - manipulate value manually (provide it when its fetched, and then change it when onChange fires)

  2. Render DatePicker only if there's nothing to fetch (new form) or once the data has been fetched and ready to be populated.

Any thoughts on what the best approach would be to accomplish this?



Solution 1:[1]

UPDATE: I no longer use React so don't have the inclination to retest this but I strongly suspect that this no longer works.

Prior answer

Rather than populate the defaultDate prop, hook the value prop to whatever you want it set to. Using this approach, you'd also want to wire up an onChange handler. It would look something like this:

onChange(event, newValue) {
  this.setState({myDate: newValue})
},
render() {
  return (
    ...
    <DatePicker value={this.state.myDate} onChange={this.onChangeHandler}>
    ...
  )
},

Alternatively, you could use the two-way binding functionality using React's LinkedStateMixin and the DatePicker's valueLink prop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1