I’m building an OTP input component in React Native with four TextInput
boxes, but I’m facing an issue where the cursor is not centered inside the box. Instead, it’s aligned to the right side of the box.
Here’s the relevant code I’m using:
<View style={styles.otpContainer}>
{[...new Array(4)].map((_, index) => (
<TextInput
ref={ref => { inputs.current[index] = ref; }}
style={[styles.otpInput, focusedIndex === index && { borderColor: tertiary }, emptyOtp && { borderColor: '#D00000' }, invalidOtp && { borderColor: '#D00000' }]}
key={index}
keyboardType="number-pad"
maxLength={1}
selectTextOnFocus
contextMenuHidden
testID={`OTPInput-${index}`}
onChangeText={text => handleChangeText(text, index)}
onKeyPress={e => handleKeyPress(e, index)}
placeholder={focusedIndex !== index ? '•' : ''}
onFocus={() => setFocusedIndex(index)}
onBlur={() => setFocusedIndex(-1)}
/>
))}
</View>
otpContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
marginTop: 40,
textAlign: 'center',
},
otpInput: {
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 8,
paddingHorizontal: 16,
textAlign: 'center',
fontSize: 24,
color: '#000',
lineHeight: 55,
width: 55,
height: 55,
}
The TextInput
cursor seems to be slightly off-center, leaning towards the right side. I’ve already ensured that the textAlign: 'center'
is set, but it still doesn’t work as expected.
Things I’ve tried:
- Removing padding and adjusting
lineHeight
. - Ensuring
width
andheight
are consistent withfontSize
. - Adjusting
textAlign
properties.
Has anyone faced this issue before or have any suggestions for fixing the cursor alignment?
texta-align: center
, this most likely means the value of the input field isn't actually empty, but probably a space character ...?textAlign: 'center'
, it aligns to the left instead of the center. How can I fix this and keep the cursor centered?