SonBrooks
SonBrooks

Reputation: 64

Focus on Input when DIV is clicked

Using React, I am trying to focus on an input element when certain buttons/elements are clicked. I need the ability to switch focus after render multiple times.

For example, If I click a name button, the name input box should focus. If I click the address button, the address input box should focus.

I'm familiar doing this with jQuery but it does not seem to behave as expected with React.js.

EDIT:

I am trying to use a button to open a menu. When the menu opens, I want the focus to automatically be on an input field.

I've tried the following:

willFocus(name) {
  if(name==='nameButton') {
  oDocument.getElementById('nameInput').focus();
}

Upvotes: 0

Views: 3966

Answers (4)

meteorBuzz
meteorBuzz

Reputation: 3200

Create a ref to the input field you want to be able to apply focus. I've named it textInput. I've used es6 syntax here.

<input
  type="text"
  ref={node => {
     this.textInput = node 
  }
}/>

Now you have reference to the node and can now access the input element from anywhere in the component.

To apply the focus in this input element, is as simple as this.textInput.focus()

Create a function that will apply the focus method to the node being referenced.

 handleMenuClick() {
   this.textInput.focus()
 }

Now you can call this function when someone clicks the menu button for example

<div 
 onClick={this.handleMenuClick.bind(this)}
> I AM MENU TITLE </div>

Upvotes: 4

szymonm
szymonm

Reputation: 1051

You could use The ref Callback Attribute. Taking an example of an input:

render() {
  // Use the `ref` callback to store a reference to the text input DOM
  // element in this.textInput.
  return (
    <div>
      <input
        type="text"
        ref={(input) => { this.textInput = input }}
      />
      ...
    </div>
  )
}

Then, you are able to explicitly focus the input by:

this.textInput.focus();

Upvotes: 0

Matt Spinks
Matt Spinks

Reputation: 6700

One very simple way is to use a <label> element:

<div>
<label for='input1'>Click here</label>
<input type='text' id='input1' />
</div>
<div>
<label for='input2'>Click here</label>
<input type='text' id='input2' />
</div>
<div>
<label for='input3'>Click here</label>
<input type='text' id='input3' />
</div>

Working example: https://jsfiddle.net/kq3okzas/

Upvotes: 2

nvioli
nvioli

Reputation: 4219

Use label. No javascript necessary.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

Upvotes: 0

Related Questions