简体   繁体   中英

How to focus in SearchBox of office ui fabric react

I am unable to make a focus inside a searchbox of Office UI Fabric React component.

I have a DialogBox where I am having a searchbox. This dialog box I trigger on button click and I wants the focus to be inside the searchbox once the dialog is there.

I have tried the mostly what is mentioned in the documentation of Office UI Fabric.

So, what I have tried uptill now:

private _searchBoxRef = React.createRef<ISearchBox>();

My SearchBox component looks like:

<SearchBox
  componentRef={this._searchBoxRef}
  placeholder="Ask a question"
  iconProps={{ iconName: 'Chat' }} />

And in the componentDidMount hook:

this._searchBoxRef.current.focus();

I am trying to make a focus inside the searchBox.

I have followed the documentation under the link: React Guidelines for Ref Usage

Does someboby have a clue what I am doing wrong here or something I am missing??

So, I found the answer after trying out few things.

The problem was, even though I was trying to make focus inside componentDidMount(), I found that the DOM was still not ready and my searchbox inside my modal was not there.

Two things could be done here,

  1. Either, wait for some time with SetTimeout and then tried to make focus
  2. Can use componentDidUpdate, if setting the state which is re-rendering the component. This might also give hickups if DOM is not ready, so keep this in mind.

Hope this will help someone.

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