diff --git a/packages/react-instantsearch-dom/src/components/SearchBox.js b/packages/react-instantsearch-dom/src/components/SearchBox.js index 49ed5c0be3..b779757d6a 100644 --- a/packages/react-instantsearch-dom/src/components/SearchBox.js +++ b/packages/react-instantsearch-dom/src/components/SearchBox.js @@ -82,8 +82,10 @@ class SearchBox extends Component { isSearchStalled: PropTypes.bool, showLoadingIndicator: PropTypes.bool, - // For testing purposes - __inputRef: PropTypes.func, + inputRef: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.exact({ current: PropTypes.object }), + ]), }; static defaultProps = { @@ -133,8 +135,11 @@ class SearchBox extends Component { onInputMount = input => { this.input = input; - if (this.props.__inputRef) { - this.props.__inputRef(input); + if (!this.props.inputRef) return; + if (typeof this.props.inputRef === 'function') { + this.props.inputRef(input); + } else { + this.props.inputRef.current = input; } }; diff --git a/packages/react-instantsearch-dom/src/components/__tests__/SearchBox.js b/packages/react-instantsearch-dom/src/components/__tests__/SearchBox.js index 86ad882582..12183ee36b 100644 --- a/packages/react-instantsearch-dom/src/components/__tests__/SearchBox.js +++ b/packages/react-instantsearch-dom/src/components/__tests__/SearchBox.js @@ -174,7 +174,7 @@ describe('SearchBox', () => { null} focusShortcuts={['s', 84]} - __inputRef={node => { + inputRef={node => { input = node; }} /> @@ -295,4 +295,39 @@ describe('SearchBox', () => { expect(wrapper.instance().input.focus).toHaveBeenCalled(); expect(wrapper.state()).toEqual({ query: '' }); }); + + it('should point created refs to its input element', () => { + const inputRef = React.createRef(); + const wrapper = mount( + null} inputRef={inputRef} /> + ); + + const refSpy = jest.spyOn(inputRef.current, 'focus'); + + // Trigger input.focus() + wrapper.find('form').simulate('reset'); + + expect(refSpy).toHaveBeenCalled(); + expect(inputRef.current.tagName).toEqual('INPUT'); + }); + + it('should return a ref when given a callback', () => { + let inputRef; + const wrapper = mount( + null} + inputRef={ref => { + inputRef = ref; + }} + /> + ); + + const refSpy = jest.spyOn(inputRef, 'focus'); + + // Trigger input.focus() + wrapper.find('form').simulate('reset'); + + expect(refSpy).toHaveBeenCalled(); + expect(inputRef.tagName).toEqual('INPUT'); + }); });