Skip to content

Commit

Permalink
fix(Ref): update node if it was changed (#3474)
Browse files Browse the repository at this point in the history
  • Loading branch information
layershifter authored Mar 4, 2019
1 parent d6f20f9 commit 383bcd7
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/addons/Ref/RefFindNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,23 @@ export default class RefFindNode extends Component {
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}

prevNode = null

componentDidMount() {
// eslint-disable-next-line react/no-find-dom-node
handleRef(this.props.innerRef, findDOMNode(this))
this.prevNode = findDOMNode(this)

handleRef(this.props.innerRef, this.prevNode)
}

componentDidUpdate() {
// eslint-disable-next-line react/no-find-dom-node
const currentNode = findDOMNode(this)

if (this.prevNode !== currentNode) {
this.prevNode = currentNode
handleRef(this.props.innerRef, currentNode)
}
}

componentWillUnmount() {
Expand Down
32 changes: 32 additions & 0 deletions test/specs/addons/Ref/RefFindNode-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,37 @@ describe('RefFindNode', () => {
innerRef.should.have.been.calledOnce()
innerRef.should.have.been.calledWithMatch(node)
})

it('passes an updated node', () => {
const innerRef = sandbox.spy()
const wrapper = mount(
<RefFindNode innerRef={innerRef}>
<div />
</RefFindNode>,
)

innerRef.should.have.been.calledOnce()
innerRef.should.have.calledWithMatch({ tagName: 'DIV' })

wrapper.setProps({ children: <button /> })
innerRef.should.have.been.calledTwice()
innerRef.should.have.calledWithMatch({ tagName: 'BUTTON' })
})

it('skips an update if node did not change', () => {
const innerRef = sandbox.spy()
const wrapper = mount(
<RefFindNode innerRef={innerRef}>
<div />
</RefFindNode>,
)

innerRef.should.have.been.calledOnce()
innerRef.should.have.calledWithMatch({ tagName: 'DIV' })

wrapper.setProps({ children: <div /> })
innerRef.should.have.been.calledOnce()
innerRef.should.have.calledWithMatch({ tagName: 'DIV' })
})
})
})

0 comments on commit 383bcd7

Please sign in to comment.