with React state it was easy to set new value which was condition for render some input and then focus to that input with state callback.
handleToggleInput() {
const showInput = !this.state.showInput
this.setState({ showInput }, () => showInput && this.refs.input.focus())
}
render() {
if(this.state.showInput) {
<input ref="input" type="text />
}
}
Now when switching to Mobx it is not possible
@observable showInput = false;
handleToggleInput() {
this.showInput = !this.showInput
this.showInput && this.refs.input.focus()
}
render() {
if(this.showInput) {
<input ref="input" type="text />
}
}
This will fail, because React did not yet rerender component with input. Is there any way how wait and detect when rerender is done?
The callback in setState
will run after the state is set and the component is re-rendered. MobX has no equivalent. So use this method to do the focus after React has re-rendered the UI.
componentDidUpdate: function(prevProps, prevState){
this.refs.input.focus();
},
To run code immediately after first render
componentDidMount: function(){
this.refs.input.focus();
},
React set focus on input after render
https://facebook.github.io/react/docs/react-component.html#componentdidupdate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With