Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use measureLayout to calculate scrolling #13499

Merged
merged 3 commits into from
Dec 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 6 additions & 27 deletions src/components/Form.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ 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 @@ -109,21 +108,6 @@ class Form extends React.Component {
return _.first(_.keys(hasStateErrors ? this.state.erorrs : this.props.formState.errorFields));
}

setPosition(element, position) {
// Some elements might not have props defined, e.g. Text
if (!element.props) {
return;
}

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 @@ -268,16 +252,7 @@ class Form extends React.Component {
ref={el => this.form = el}
>
<View style={[this.props.style]}>
{_.map(this.childrenWrapperWithProps(this.props.children), child => (
<View
key={child.key}
onLayout={(event) => {
this.setPosition(child, event.nativeEvent.layout.y);
}}
>
{child}
</View>
))}
{this.childrenWrapperWithProps(this.props.children)}
{this.props.isSubmitButtonVisible && (
<FormAlertWithSubmitButton
buttonText={this.props.submitButtonText}
Expand All @@ -289,10 +264,14 @@ 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();
}

// We substract 10 to scroll slightly above the input
if (focusInput.measureLayout && typeof focusInput.measureLayout === 'function') {
focusInput.measureLayout(this.form, (x, y) => this.form.scrollTo({y: y - 10, animated: false}));
}
}}
containerStyles={[styles.mh0, styles.mt5]}
enabledWhenOffline={this.props.enabledWhenOffline}
Expand Down