0

Below is the code:

export class Editor extends Component {
   constructor(props) {
      super(props);
      this.state = {
         name: ""
      }
   }

   handleChange = (event) => {
        event.persist();
        this.setState({ name: event.target.value });
   }

   render() {
      ...
       <input name="name" autoFocus={true} value={this.state.name} onChange={this.handleChange} />
       <button onClick={this.handleAdd}>
          Add
       </button>
   }
}

So the first time the component renders, the input element did have focus since I use autoFocus={true}. But after I clicked the button, the focus didn't go back to the input but stayed on the button. My question is:

Why the input didn't regain the focus? Since onClick handler updated the component's state, which makes the component re-render again, when the component re-renders, isn't that autoFocus={true} will re-apply as well?

2 Answers2

1

If you use autoFocus, only the initial render will have focus. Since React intelligently only re-renders elements that have changed, the autofocus attribute isn't reliable in all cases.

It would be easier if you used a functional component, but you can do the following in the class component.

export class Editor extends Component {
   constructor(props) {
      super(props);
      this.state = {
         name: ""
      }
      this.nameInput = React.createRef();
   }

   handleChange = (event) => {
        event.persist();
        this.setState({ name: event.target.value });
   }

   handleAdd = () => {
       this.nameInput.current.focus();
   }

   render() {
      ...
       <input ref={this.nameInput} name="name" autoFocus={true} value={this.state.name} onChange={this.handleChange} />
       <button onClick={this.handleAdd}>
          Add
       </button>
   }
}

If you want to see another approach you can look here: https://stackoverflow.com/a/54159564/5562701

and

https://davidwalsh.name/react-autofocus

Ozan Manav
  • 429
  • 4
  • 18
  • Thanks for your answer. I know this approach which is called uncontrolled form components which uses refs. SO just need to confirm with you: even autofocus changes, the input element is still considered as unchanged? is it smart or dumb? –  Nov 02 '19 at 12:31
  • in fact, it needs to be solved by the react side, but they have not yet found a solution. We need an approach like this, but still PR has not been made and merge. https://github.com/facebook/react/issues/5534#issuecomment-290417284 And you know, by the way, you can do this focus in componentDidUpdate, or useEffect in the functional component. – Ozan Manav Nov 02 '19 at 12:40
0

No, it does not because react only re-renders elements that have changed, David Walsh explains this very well, you may want to check this. Happy coding!

Soheb
  • 788
  • 6
  • 11