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>
);
}
}