Skip to content

Commit 83df63b

Browse files
committed
Fix controlled mode displaying wrong value sometimes.
Fixes #24
1 parent ea56e2e commit 83df63b

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

src/TimeInput.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,15 +55,19 @@ class TimeInput extends React.Component {
5555

5656
getFormattedValue = () => {
5757
const { mode, placeholder } = this.props
58-
const { value, hasChanged } = this.state
58+
const { hasChanged } = this.state
5959

6060
const is12h = mode === '12h'
6161

6262
if (placeholder && !hasChanged) return placeholder
6363

64-
// Allow a null/undefined value for controlled inputs
65-
if (this.props.hasOwnProperty('value') && this.props.value == null) {
66-
return ''
64+
let value = this.state.value
65+
if (this.props.hasOwnProperty('value')) {
66+
if (this.props.value == null) {
67+
// Allow a null/undefined value for controlled inputs
68+
return ''
69+
}
70+
value = this.props.value
6771
}
6872

6973
const { hours, isPm } = formatHours(value.getHours(), mode)

src/TimeInput.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,18 @@ describe('<TimeInput />', () => {
7070
const tree = mount(<TimeInput value={null} />)
7171
expect(getValue(tree)).toBe('')
7272
})
73+
74+
it('always ignores the internal state if a value is specified', () => {
75+
const UnstyledTimeInput = unwrap(TimeInput)
76+
const tree = mount(<UnstyledTimeInput classes={{}} value={new Date(2017, 10, 15, 14, 42, 0, 0)} mode='24h' />)
77+
78+
// simulate time selection
79+
tree.instance().handleChange(new Date(2017, 10, 15, 13, 37, 0, 0))
80+
tree.instance().handleOk()
81+
82+
// controlled component, so value should stay as specified by the prop (issue #11)
83+
expect(getValue(tree)).toBe('14:42')
84+
})
7385
})
7486

7587
describe('uncontrolled mode', () => {

0 commit comments

Comments
 (0)