Frank Jusnes
Frank Jusnes

Reputation: 185

How to set focus across an hierarchy in React

In my React chat-application I have a hierarchy of components like this:

ThreadList
    Thread
        Reply
            ReplyMenu
                ReplyButton
                    <button onClick="?" />

        Reply
        Reply
        .
        NewReply
            <input ref={(input) => {this.replyInput = input}}>

What I want is that when I press the ReplyButton, focus should be set to the input inside the NewReply component. Can anyone explain to me how to accomplish this in React. I have seen examples where the component setting the focus is an immediate parent of the input, but not in a different part of the hierarchy.

Thanks, Frank

Upvotes: 0

Views: 834

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281626

You will have to pass on the click event to the parent Reply component and then call the focus function from there. So you also need to pass on this function from Reply component to each of this child till the ReplyButton component

Somthing like

Reply

focusNewReply() {
     this.replyInput.focus();
}

ReplyMenu

focusNewReply() {
    this.props.focusNewReply();
}

ReplyButton

<button onClick={()=>{this.props.focusNewReply()}}>

Upvotes: 1

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

Did you try calling focus() on the input?

  render(){
  const _this = this;
  <button onClick={() => _this.replyInput.focus()} />
}

Upvotes: 0

Related Questions