Question: Focus an input after an action is dispatched
See original GitHub issueI have a button that dispatches an action that toggles a boolean in the store. As a result, an input is rendered in the component. I want to focus on that input after the button is clicked, but I can’t do it immediately because the this.refs
is not updated until the new props are received.
If this is handled in componentDidUpdate
, all subsequent action will keep triggering the focus
, so that’s not a good solution.
componentDidUpdate() {
const { isComposing } = this.props
if (isComposing) {
this.refs.composer.focus()
}
}
Example: http://jsbin.com/nerexi/2/edit?js,console,output
Another potential solution is a combination of focusing from the componentDidMount
and also from the button callback: http://jsbin.com/viwive/3/edit?js,console,output
Not a big fan of this as it seems like the container component’s job to focus.
However, using setState
and its callback actually allows to access the ref
, as it fires after render happens: http://jsbin.com/yiputo/1/edit?js,console,output (cleanest solution, I believe, despite the use of state
)
This question relates to any UI forced interaction that needs to happen after an action but can’t be in render
. Another example would be scrolling to an element to bottom after an action is dispatched.
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
I’d do something like
I agree callback refs are nice: https://github.com/rackt/react-redux/pull/270#issuecomment-175217424. However I’d rather use them for DOM nodes than for instances. Best not to expose instances or use their methods.
const { wasComposing: isComposing } = prevProps
maybe? 😃