Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mobx and React. How to handle focus input after observable change?

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?

like image 513
Schovi Avatar asked Sep 19 '25 04:09

Schovi


1 Answers

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

like image 108
Jesvin Jose Avatar answered Sep 21 '25 21:09

Jesvin Jose