0
votes

I use a Function component to render a component. But the input control loses focus whenever the state is set.

How to change the below code so that the input doesnt' lose focus? I'd need the component to be a Function component.

There are 10 inputs on my form so depending on which text box has changed, it should place the focus on the changed text box after being rendered.

in the changeHandler(event), I know the event which contains the target property which refers to the changed text box so somehow I'd need to set the focus to the target input element after the state being rendered.

maybe I should define a class level variable and set the target to that.

import React, {Component} from 'react';

export default class PlaybackPassword extends Component{   

constructor(props) {
        super(props);
          this.state = {
            setting: {}
          }
        this.focusElement = null;    
        this.changeHandler= this.changeHandler.bind(this); 
    }

    componentDidUpdate()
    {
      if (this.focusElement != null)
      this.focusElement.focus();
     }

     changeHandler(event)
        {  
            this.focusElement = event.target;
            var setting = this.state.setting;
            setting.SelectedValue = event.target.value;  
            this.setState({setting : setting});
        }
    render() {
            var parent = this;
            function Password(props)
            {
                return (<div className="password">
                  <input type="password" 
                    value={props.selectedValue} onChange={parent.changeHandler} /> 
                </div>);
            } 
            return (
            <div className="playbackPassword">
                <Password selectedValue={this.state.setting.SelectedValue}  /> 
            </div>         
            );
        }
}
1
You can pass the autoFocus property to the input element. If the input loses focus at any point during the update, you can set a ref and manually focus on it in the componentDidUpdate lifecycle method. - djfdev
Can you provide a sample code? - Dynamic
Just add autoFocus as a property right after you assign the onChange handler. stackoverflow.com/questions/28889826/… - djfdev
If you clean up your code a little bit, I don't think you will have the auto focus problem: Password component should be moved outside render. - vijayst

1 Answers

0
votes

In the example code, you are defining (i.e., creating) a new function Password on every render. This means that your <Password> component will be a brand new component every time.

The key is to define your function once, outside of the render function, so that React can track that the <Password> component is in fact the same component between renders.

Example: https://codesandbox.io/s/nn2nwq2lzp

Note: you won't be able to use parent but will need to pass a prop instead.