Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I focus a Search component programmatically in Semantic UI React?

As the question says it all, I cannot focus the Semantic UI Search component programmatically.

I tried:

<Search
     category
     fluid
     loading={isItemLoading}
     onResultSelect={this.handleItemResultSelect}
     onSearchChange={this.handleItemSearchChange}
     placeholder='Search by name'
     results={itemResults}
     value={itemValue}
     ref={input => { this.itemSearch = input; }} />

and

this.itemSearch.setState({ focus: true, open: true });

This opens the results but does not focus the input for the user to retype.

like image 424
Yehan Pemarathne Avatar asked Jan 04 '23 06:01

Yehan Pemarathne


2 Answers

For those who stumble on this old question: Search now has input prop. It looks like it accepts the same props as the semantic Input component. Get the Search's Input ref like this:

<Search input={{ref: r => this.searchInputRef = r}} />

And then use it like this:

focusSearchInput() {
  if (this.searchInputRef.focus) {
    this.searchInputRef.focus();
  }
}

It works for me

like image 104
dletin Avatar answered Jan 05 '23 21:01

dletin


This worked for me

import React, { useEffect } from 'react'
import { Search} from 'semantic-ui-react'

const Form = (props) => {
   const searchRef = React.createRef();

   useEffect(() => {
      searchRef.current.focus();
   }, [])

   return (
      <div>
         <Search input={{ref: searchRef}} />
      </div>
   )
}

export default Form
like image 36
Julio Ojeda Avatar answered Jan 05 '23 20:01

Julio Ojeda