TeamWertarbyte / material-ui-search-bar

Material design search bar
https://mui.wertarbyte.com/#material-ui-search-bar
MIT License
260 stars 82 forks source link

Any way to autoFocus? #15

Closed tgoldenberg closed 7 years ago

tgoldenberg commented 7 years ago

Any way to have the input focus automatically?

Not able to get any ref so unsure how to activate focus

Thanks.

leMaik commented 7 years ago

Just added focus() and blur() methods, so you can get a ref and call .focus() right after the component is mounted.

tgoldenberg commented 7 years ago

Could you give an example? I tried this and not getting anything:

<SearchBar
            hintText="Search..."
            open={true}
            ref={el => el.focus()}
            dataSource={this.props.autocompleteOptions}
            onChange={(e) => console.log('> On change: ', e)}
            onRequestSearch={() => console.log('> Request change: ')}
            menuStyle={{ minWidth: 500 }}
            popoverProps={{ style: { minWidth: 500, top: 64, left: 0, right: 0 }}}
            listStyle={{ minWidth: 500 }}
            anchorOrigin={{ vertical: 64, horizontal: 0 }}
            menuProps={{ maxHeight: 400 }}
            maxSearchResults={10}
            openOnFocus={true}
            searchIcon={<SearchIcon color="#bbb" />}
            style={{ boxShadow: 'none', height: 64, alignItems: 'center' }}
            textFieldStyle={{ fontSize: 22 }}
          />
tgoldenberg commented 7 years ago

The ref doesn't show a focus attribute either, so not sure how this supposed to be implemented:

screenshot 2017-08-24 14 39 23
tgoldenberg commented 7 years ago

I think you something like this in the constructor ?

constructor() {
  this.handleFocus = this.handleFocus.bind(this);
}
leMaik commented 7 years ago

The ref has a focus method in its prototype. And nope, I don't need to bind this in the constructor.

You might not be able to call focus() directly in the ref callback. Just try to save the ref in your class and call it in the componentDidMount handler. Just tried this and it works fine.

tgoldenberg commented 7 years ago

Got it, thanks. Turns out I was still on 0.3.0, upgrading fixed it for me.

Also, had to add a short setTimeout for it to work effectively, just FYI.

DrSkunk commented 6 years ago

Is it possible that this doesn't work anymore with 1.0.0-beta.7 ?

If added the following:

<SearchBar
    value={this.state.value}
    ref={sb => (this.searchBar = sb)}
    onChange={newValue => this.setState({ value: newValue })}
    onRequestSearch={this.search}
/>

then in componentDidMount()

  componentDidMount = () => {
    this.searchBar.focus()
  }

But no dice. When logging this.searchBar it doesn't show the focus() function, also after a timeout.

MartinJohannesNilsen commented 3 years ago

Someone with a solution here with React Hooks?