1

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the idea! I think the current impl has a slight bug, in that every update will focus the component - a bit annoying. I just noticed that componentDidUpdate gives you the previous props/state, which enables one to focus() only on this.state.show transitions.
Yes, needed a bit more logic depending on the use case, but using the refs is the trick! You can also use jquery with the refs for example: $(React.findDOMNode(this.refs.myRef)).show();
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.