Search code examples
reactjsreact-nativepassword-confirmation

Automatically show keyboard on first render of react-native-confirmation-code-field


I am using the react-native-confirmation-code-field package. I want the keyboard to be showing as soon as the screen renders and the first cell in focus. Any ideas how to do this?

enter image description here

Edit: Including my code below:

export default function ConfirmationCode({ route, navigation }) {

  const [value, setValue] = useState("")
  const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT })
  const [props, getCellOnLayoutHandler] = useClearByFocusCell({value, setValue})

  return (
        <CodeField
          ref={ref}
          {...props}
          value={value}
          onChangeText={setValue}
          cellCount={CELL_COUNT}
          rootStyle={styles.codeFieldRoot}
          keyboardType="number-pad"
          textContentType="oneTimeCode"
          renderCell={({ index, symbol, isFocused }) => (
            <Text
              key={index}
              style={[styles.cell, isFocused && styles.focusCell]}>
              {symbol || (isFocused ? <Cursor /> : null)}
            </Text>
          )
          }
        />
    )
}



Solution

  • So it turns out that CodeField does have an autoFocus property, my bad. The solution is simply to add autoFocus={true} as a prop to the CodeField component:

            <CodeField
              ref={ref}
              {...props}
              autoFocus={true}
              value={value}
              onChangeText={setValue}
              cellCount={CELL_COUNT}
              rootStyle={styles.codeFieldRoot}
              keyboardType="number-pad"
              textContentType="oneTimeCode"
              renderCell={({ index, symbol, isFocused }) => (
                <TextInput
                  key={index}
                  ref={index === 0 && textInputRef)
                  style={[styles.cell, isFocused && styles.focusCell]}>
                  {symbol || (isFocused ? <Cursor /> : null)}
                </TextInput>
              )
              }
            />