Skip to content

Commit 2e752ff

Browse files
feat(focus): Add ref to Select component and a focus function
1 parent b847294 commit 2e752ff

1 file changed

Lines changed: 25 additions & 14 deletions

File tree

index.js

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,21 @@ class Geocoder extends PureComponent {
1515
rateLimit: PropTypes.number,
1616
search: PropTypes.func,
1717
value: PropTypes.object
18-
};
18+
}
1919

2020
static defaultProps = {
2121
featureToLabel: (feature) => feature.properties.label,
2222
featureToValue: (feature) => `${feature.properties.label}-${feature.geometry.coordinates.join(',')}`,
2323
search: mapzenSearch
24-
};
24+
}
2525

26-
options = {};
26+
options = {}
2727

2828
state = {
2929
value: this.props.value || null
30-
};
30+
}
31+
32+
_throttledLoadOptions = throttle(this.loadOptions, this.props.rateLimit || 500)
3133

3234
cacheOptions (options) {
3335
options.forEach((o) => {
@@ -39,6 +41,10 @@ class Geocoder extends PureComponent {
3941
if (!shallowEqual(nextProps.value, this.props.value)) {
4042
this.setState({value: nextProps.value})
4143
}
44+
45+
if (this.props.rateLimit !== nextProps.rateLimit) {
46+
this._throttledLoadOptions = throttle(this.loadOptions, this.props.rateLimit || 500)
47+
}
4248
}
4349

4450
featureToOption = (feature) => {
@@ -48,7 +54,11 @@ class Geocoder extends PureComponent {
4854
label: featureToLabel(feature),
4955
value: featureToValue(feature)
5056
}
51-
};
57+
}
58+
59+
focus () {
60+
this.select.focus()
61+
}
5262

5363
loadOptions = (input) => {
5464
const {apiKey, focusLatlng, boundary, search} = this.props
@@ -62,27 +72,28 @@ class Geocoder extends PureComponent {
6272
this.cacheOptions(options)
6373
return {options}
6474
})
65-
};
66-
67-
throttleLoadOptions = (loadOptions) => {
68-
return throttle(loadOptions, this.props.rateLimit || 500)
69-
};
75+
}
7076

71-
onChange = (value) => {
77+
_onChange = (value) => {
7278
this.setState({value})
7379
this.props.onChange && this.props.onChange(value && this.options[value.value])
74-
};
80+
}
81+
82+
_saveRef = (select) => {
83+
this.select = select
84+
}
7585

7686
render () {
7787
return (
7888
<Select.Async
7989
autoload={false}
8090
cacheAsyncResults={false}
8191
filterOptions={false}
82-
loadOptions={this.throttleLoadOptions(this.loadOptions)}
92+
loadOptions={this._throttledLoadOptions}
8393
minimumInput={3}
8494
{...this.props}
85-
onChange={this.onChange}
95+
onChange={this._onChange}
96+
ref={this._saveRef}
8697
value={this.state.value}
8798
/>
8899
)

0 commit comments

Comments
 (0)