George Raveen
George Raveen

Reputation: 451

react material ui autocomplete element focus onclick

I have a material-ui autocomplete element

<Autocomplete
  id="combo-box-demo"
  autoHighlight
  openOnFocus
  autoComplete
  options={this.state.products}
  getOptionLabel={option => option.productName}
  style={{ width: 300 }}
  onChange={this.selectProduct}
  renderInput={params => (
    <TextField {...params} label="Select Product Name" variant="outlined" />
  )}
/>;

I want this element to get focus when I click a button.

I tried using references as discribed here how react programmatically focus input

It worked for other elements but not for autocomplete

please help

Upvotes: 20

Views: 24338

Answers (2)

sudip lahiri
sudip lahiri

Reputation: 41

as per material ui previous version 4 or current version 5, You can simply focus autocomplete input element using autoFocus props, if autoFocus is set to true then input element will be focused on each first mount of autocomplete component.

const [query, setQuery] = useState('');

<Autocomplete
.....
 renderInput={(params) => {
  const { InputLabelProps, InputProps, ...rest } = params;
  return <InputBase
    {...params.InputProps}
                    {...rest} 
                     name="query"
                      value={query}  
                      onChange={handleSearch}
                      autoFocus

   />

}}

/>

// it is just an example , you can handle below function as per your wish

function handleOnSearch({ currentTarget = {} }) {
    const { value } = currentTarget;
    setQuery(value);
  }

If you want to open an autocomplete input once a button is clicked :-

//button to be clicked to open autocomplete input
const clickButton=()=>{
setOpen(true)
}

const handleClose =()=>{
setOpen(false)
}

<Dialogue
close={handleClose}
open={open}

>
<DialogActions>
 <Autocomplete
    .....
     renderInput={(params) => {
      const { InputLabelProps, InputProps, ...rest } = params;
      return <InputBase
        {...params.InputProps}
                        {...rest} 
                         name="query"
                          value={query}  
                          onChange={handleSearch}
                          autoFocus
    
       />
    
    }}
    
    />

</DialogActions>

</Dialogue>

Cheers!!!

Upvotes: 3

Dekel
Dekel

Reputation: 62546

You should save a reference to the TextField component, and use this ref to focus once another element is clicked (once some event was triggered).

let inputRef;

<Autocomplete
  ...
  renderInput={params => (
    <TextField
      inputRef={input => {
        inputRef = input;
      }}
    />
  )}
/>
<button
  onClick={() => {
    inputRef.focus();
  }}

Here is a link to a working example: https://codesandbox.io/s/young-shadow-8typb

You can play with the openOnFocus property of the Autocomplete to decide if you just want focus on the input or you want the dropdown of the autocomplete to open.

Upvotes: 26

Related Questions