Form fields lose focus when input value changes in react

Posted by Ramesh Singh | Updated on

Form fields lose focus when input value changes in react. The problem is pretty straightforward, you are creating a FormWithConditionals component in your render method and in your onChange handler you setState which triggers a re-render and thus a new instance of FormWithConditionals is created and hence it loses focus. You need to move this instance out of render method and perhaps out of the component itself since it uses static values.

As schema, uiSchema and rules are passed as props to the ConditionalForm, you can create an instance of FormWithConditionals in constructor function and use it in render like this

}

)
}

class ConditionalForm extends React.Component {

constructor (props) {
super(props);
this.state = {
formData: {},
showModel: true
};
const { schema, uiSchema, rules } = props;
this.FormWithConditionals = applyRules(schema, uiSchema, rules, Engine)(Form);
this.handleFormDataChange = this.handleFormDataChange.bind(this);
this.handleShowModelChange = this.handleShowModelChange.bind(this);
}

handleShowModelChange (event) {
this.setState({showModel: event.target.checked});
}

handleFormDataChange ({formData}) {
this.setState({formData});
}

render () {
const FormWithConditionals = this.FormWithConditionals;
return (


);
}
}

ConditionalForm.propTypes = {
schema: PropTypes.object.isRequired,
uiSchema: PropTypes.object.isRequired,
rules: PropTypes.array.isRequired
};

ConditionalForm.defaultProps = {
uiSchema: {},
rules: []
};

If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.

Related Questions & Answers