Reputation: 83358
My component has a list of child components, each with a text input. My redux store has an activeIndex property which stores which input is being edited. When they hit enter, redux dispatches and updates the active index appropriately. The problem is that the focus is not changing. This was my original (non working) code.
<input autoFocus={this.props.index == this.props.activeInput}
This code DID set the initial focus correctly, but did not update.
Am I correct in assuming that React's dom-diffing algorithm doesn't include the focus information, and therefore decided nothing needed to be re-rendered? My solution wound up being this:
<input ref='input' autoFocus={this.props.index == this.props.activeInput}
componentDidUpdate(){
if (this.props.index == this.props.activeInput){
ReactDOM.findDOMNode(this.refs.input).focus();
}
}
which does work. Would this be the ideal solution in my case, or is there a more "react" way of accomplishing this?
Upvotes: 0
Views: 180
Reputation: 14101
The reason your component does not update focus is not because of react's diff engine. If your props are different, react will re-render the component. Your issue stems (I think) from the way autofocus works: autofocus is only checked and applied on initial rendering of the page.
Your component is rerendered by react, but the second time around, HTML ignores the autofocus attribute.
So your second solution is a good react-y way to solve.
Upvotes: 2