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

Commit

Permalink
feat(SearchBox): provide input element ref (#2913)
Browse files Browse the repository at this point in the history
* feat: provide input element ref

* fix: allow both ref and callback

* refactor: clean up SearchBox

* fix: remove HTMLInputElement from PropType
  • Loading branch information
ojeytonwilliams authored Apr 9, 2020
1 parent 4783469 commit b41bff2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
13 changes: 9 additions & 4 deletions packages/react-instantsearch-dom/src/components/SearchBox.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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;
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ describe('SearchBox', () => {
<SearchBox
refine={() => null}
focusShortcuts={['s', 84]}
__inputRef={node => {
inputRef={node => {
input = node;
}}
/>
Expand Down Expand Up @@ -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(
<SearchBox refine={() => 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(
<SearchBox
refine={() => 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');
});
});

0 comments on commit b41bff2

Please sign in to comment.