Skip to content
This repository has been archived by the owner on Dec 23, 2022. It is now read-only.

Commit

Permalink
Replace componentWillReceiveProps with getDerivedStateFromProps.
Browse files Browse the repository at this point in the history
Might be related to #258
  • Loading branch information
leMaik committed Jan 20, 2019
1 parent ab39611 commit 64d96e5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/ChipInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ class ChipInput extends React.Component {
focusedChip: null,
inputValue: '',
isClean: true,
isFocused: false
isFocused: false,
prevPropsValue: []
}

constructor (props) {
Expand All @@ -171,16 +172,22 @@ class ChipInput extends React.Component {
clearTimeout(this.inputBlurTimeout)
}

componentWillReceiveProps (nextProps) {
if (nextProps.disabled) {
this.setState({ focusedChip: null })
static getDerivedStateFromProps (props, state) {
let newState = null

if (props.value && props.value.length !== state.prevPropsValue.length) {
if (props.clearInputValueOnChange) {
newState = { inputValue: '' }
} else {
newState = { prevPropsValue: props.value }
}
}

// Lets assume that if the chips have changed, the inputValue should be empty
// otherwise, we would need to make inputValue a controlled value. which is quite messy
if (nextProps.value && this.props.clearInputValueOnChange && nextProps.value.length !== this.props.value.length) {
this.setState({ inputValue: '' })
if (props.disabled) {
newState = { ...newState, focusedChip: null }
}

return newState
}

/**
Expand Down
20 changes: 20 additions & 0 deletions src/ChipInput.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,26 @@ describe('uncontrolled mode', () => {
})
})

describe('controlled mode', () => {
it('clears the input when the value changes if clearInputValueOnChange is set', () => {
const tree = mount(
<ChipInput value={['foo']} clearInputValueOnChange />
)
tree.find('input').simulate('change', { target: { value: 'bar' } })
tree.setProps({ value: ['foo', 'bar'] })
expect(tree.find('input').getDOMNode().value).toBe('')
})

it('keeps the input when the value changes if clearInputValueOnChange is not set', () => {
const tree = mount(
<ChipInput value={['foo']} />
)
tree.find('input').simulate('change', { target: { value: 'bar' } })
tree.setProps({ value: ['foo', 'bar'] })
expect(tree.find('input').getDOMNode().value).toBe('bar')
})
})

describe('chip focusing', () => {
function getFocusedChip (tree) {
return tree.find('Chip').filterWhere((chip) => chip.getDOMNode().style.backgroundColor !== '')
Expand Down

0 comments on commit 64d96e5

Please sign in to comment.