Skip to content

Commit

Permalink
fix(withNextInputAutoFocus): fix crash if no focusable input is found
Browse files Browse the repository at this point in the history
  • Loading branch information
Almouro committed Dec 15, 2018
1 parent ea91538 commit 5576577
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions src/withNextInputAutoFocus.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@ const getInputs = children =>
if (child && child.props && child.props.children) {
return partialInputs.concat(getInputs(child.props.children));
}
if (child && child.props && !!child.props.name) return partialInputs.concat(child);
if (child && child.props && !!child.props.name)
return partialInputs.concat(child);
return partialInputs;
}, []);

export const withNextInputAutoFocusForm = (WrappedComponent, { submitAfterLastInput } = { submitAfterLastInput: true }) => {
export const withNextInputAutoFocusForm = (
WrappedComponent,
{ submitAfterLastInput } = { submitAfterLastInput: true }
) => {
class WithNextInputAutoFocusForm extends React.PureComponent {
static childContextTypes = withNextInputAutoFocusContextType;

Expand All @@ -32,24 +36,26 @@ export const withNextInputAutoFocusForm = (WrappedComponent, { submitAfterLastIn
inputNameMap;
inputRefs = {};

getInputPosition = name => this.inputs.findIndex(input => input.props.name === name);
getInputPosition = name =>
this.inputs.findIndex(input => input.props.name === name);

getChildContext = () => ({
setInput: (name, component) => {
this.inputRefs[name] = component;
},
handleSubmitEditing: name => {
const inputPosition = this.getInputPosition(name);
const isLastInput = inputPosition === this.inputs.length - 1;

if (isLastInput) {
if (submitAfterLastInput) this.props.formik.submitForm();
} else {
const nextInputs = this.inputs.slice(inputPosition + 1);
const nextFocusableInput = nextInputs.find(
element => this.inputRefs[element.props.name] && this.inputRefs[element.props.name].focus
);
const nextInputs = this.inputs.slice(inputPosition + 1);
const nextFocusableInput = nextInputs.find(
element =>
this.inputRefs[element.props.name] &&
this.inputRefs[element.props.name].focus
);

if (nextFocusableInput) {
this.inputRefs[nextFocusableInput.props.name].focus();
} else {
if (submitAfterLastInput) this.props.formik.submitForm();
}
},
getReturnKeyType: name => {
Expand All @@ -69,7 +75,10 @@ export const withNextInputAutoFocusForm = (WrappedComponent, { submitAfterLastIn
};

export const withNextInputAutoFocusInput = Input => {
class WithNextInputAutoFocusInput extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
class WithNextInputAutoFocusInput extends React.Component<
$FlowFixMeProps,
$FlowFixMeState
> {
static contextTypes = withNextInputAutoFocusContextType;

setInput = component => {
Expand Down

0 comments on commit 5576577

Please sign in to comment.