Skip to content

Instantly share code, notes, and snippets.

@tomfa
Last active July 1, 2020 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfa/942039003768f0b3d7e3e5447817621c to your computer and use it in GitHub Desktop.
Save tomfa/942039003768f0b3d7e3e5447817621c to your computer and use it in GitHub Desktop.
React Native: Focus next element on complete
import React, { useCallback, useRef, useState } from 'react';
import { TextInput } from 'react-native';
export const useInputFocus = () => {
const refs = useRef({});
const [currentFocus, setCurrentFocus] = useState('');
const focus = useCallback(
key => {
if (refs.current[currentFocus]) {
refs.current[currentFocus].blur();
}
if (refs.current[key]) {
refs.current[key].focus();
}
},
[currentFocus],
);
const setRef = name => input => {
refs.current[name] = input;
};
return { focus, setRef };
};
const Component = () => {
const { focus, setRef } = useInputFocus();
return (
<>
<TextInput
ref={setRef('name')}
onSubmitEditing={() => focus('address')}
/>
<TextInput
ref={setRef('address')}
onSubmitEditing={() => focus('phonenumber')}
/>
<TextInput
ref={setRef('phonenumber')}
/>
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment