I’m using DatePicker in the following scenario:
- Render the form that used DatePicker
- on componentDidMount, fetch form’s saved information (if it was saved previously)
- set DatePicker’s prop
defaultValue
fromundefined
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:
Have a controlled component – manipulate value manually (provide it when its fetched, and then change it when onChange fires)
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?
Advertisement
Answer
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.