Skip to content

Commit

Permalink
Merge pull request #12954 from Expensify/alberto-scroll
Browse files Browse the repository at this point in the history
Scroll to the right spot when clicking "Fix Errors"
  • Loading branch information
danieldoglas authored Dec 5, 2022
2 parents 5530ea2 + 9cf8ff3 commit 56b69d4
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/components/Form.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class Form extends React.Component {

this.inputRefs = {};
this.touchedInputs = {};
this.childPosition = {};

this.setTouchedInput = this.setTouchedInput.bind(this);
this.validate = this.validate.bind(this);
Expand Down Expand Up @@ -108,6 +109,16 @@ class Form extends React.Component {
return _.first(_.keys(hasStateErrors ? this.state.erorrs : this.props.formState.errorFields));
}

setPosition(element, position) {
if (!element.props.inputID && element.props.children) {
_.forEach(element.props.children, (child) => {
this.setPosition(child, position);
});
} else {
this.childPosition[element.props.inputID] = position;
}
}

submit() {
// Return early if the form is already submitting to avoid duplicate submission
if (this.props.formState.isLoading) {
Expand Down Expand Up @@ -249,9 +260,18 @@ class Form extends React.Component {
style={[styles.w100, styles.flex1]}
contentContainerStyle={styles.flexGrow1}
keyboardShouldPersistTaps="handled"
ref={el => this.form = el}
>
<View style={[this.props.style]}>
{this.childrenWrapperWithProps(this.props.children)}
{_.map(this.childrenWrapperWithProps(this.props.children), child => (
<View
onLayout={(event) => {
this.setPosition(child, event.nativeEvent.layout.y);
}}
>
{child}
</View>
))}
{this.props.isSubmitButtonVisible && (
<FormAlertWithSubmitButton
buttonText={this.props.submitButtonText}
Expand All @@ -263,6 +283,7 @@ class Form extends React.Component {
const errors = !_.isEmpty(this.state.errors) ? this.state.errors : this.props.formState.errorFields;
const focusKey = _.find(_.keys(this.inputRefs), key => _.keys(errors).includes(key));
const focusInput = this.inputRefs[focusKey];
this.form.scrollTo({y: this.childPosition[focusKey], animated: false});
if (focusInput.focus && typeof focusInput.focus === 'function') {
focusInput.focus();
}
Expand Down

0 comments on commit 56b69d4

Please sign in to comment.