Last active
July 1, 2020 14:40
-
-
Save tomfa/942039003768f0b3d7e3e5447817621c to your computer and use it in GitHub Desktop.
React Native: Focus next element on complete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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