Chris
Chris

Reputation: 1587

ReactJS: unhide + focus an input field

I would like to show and focus an input field at the same time. I am looking for advice on the most elegant way to do this.

The simplistic approach, which doesn't work, would be: * The element that contains the input field makes some state change which unhides the input box by setting display = ''. I got this part to work. * The element that contains the input field gets the child element, via a ref, and calls .focus() on its DOM element. This is the part that doesn't work.

I think this is because the style change (display = '') has not propagated to the real DOM, so the focus() doesn't work.

I can think of ways to fix this (the input field could have a state var isFocusing, which calls focus() only after rendering has taken place), but I would to hear if there's a more elegant way of achieving this.

Thanks!

Upvotes: 1

Views: 2940

Answers (2)

Kristofor Carle
Kristofor Carle

Reputation: 1425

componentDidUpdate(prevProps, prevState) is called immediately after updates are flushed to the DOM and it can be used to focus the input box at the right time.

componentDidUpdate(prevProps) {
  if(!prevProps.show && this.props.show){
     // We transitioned from hidden to shown. Focus the text box.
     this.refs.myInput.getDOMNode().focus();
  }
},
render(){
   return (
     <form>
        <input className={this.props.show ? 'input-shown' : 'input-hidden} />
     </form>
   );
}

There is more info in the docs here: https://facebook.github.io/react/docs/more-about-refs.html

Upvotes: 2

J. Mark Stevens
J. Mark Stevens

Reputation: 4945

Use a parent child setup with your parent sending a hide prop. In the child render if (this.props.hide) return null; or return the input. Also in the child use componentWillReceiveProps(nextProps) and set focus there.

Upvotes: 1

Related Questions