简体   繁体   中英

React semantic UI: How to set focus for input field of dropdown element

Is it possible to initially set focus to an input field of an Dropdown element?

<Dropdown
  name={name}
  placeholder='Select type'
  search
  searchInput={{ type: 'text' }}
  selection
  onChange={this.handleChange}
  options={options}
/>

So the user should be able to start typing/searching without the need of clicking on the dropdown input field...

If I understand your question correctly, you want to give your Dropdown component focus when your content is loaded?

If that is indeed the case, then you want to make use of Refs. See the following for a detailed example: Refs and the DOM

In particular:

When to Use Refs

There are a few good use cases for refs:

  • Managing focus , text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

I found react-dropdown-input which matches your description

var searchNames = ['Sydney', 'Melbourne', 'Brisbane', 
    'Adelaide', 'Perth', 'Hobart'];
//...
<DropdownInput 
    options={searchNames}
    defaultValue={this.props.initialValue} // This is what you need
    menuClassName='dropdown-input'
    onSelect={this.handleSelectName}
    placeholder='Search...'
/>

However, last commit in this dependcy was two years ago.

There is react-dropdown which seems to be more famous and update-to-date. It works similar to the previous one

import Dropdown from 'react-dropdown' const defaultOption = options[0]

import Dropdown from 'react-dropdown'
const defaultOption = options[0]
<Dropdown 
    options={options}
    onChange={this._onSelect}
    value={defaultOption} // This is what you need
    placeholder="Select an option"
/>

For a second I thought I miss understood your question and I deleted my answer. Then I read your question (twice) again and I think this is the answer you are seeking. Kindly let me know if this solves your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM