I’m working on a React Native application and I’m facing an issue with aligning a text input and its placeholder differently. I want the input text to be aligned to the right, while keeping the placeholder aligned to the left within the same input field. I’ve tried using the textAlign
property, but it’s affecting both the input text and the placeholder. Here’s the code I’ve tried:
import React, { useState } from 'react';
import { View, TextInput, StyleSheet } from 'react-native';
const MyComponent = () => {
const [text, setText] = useState('');
return (
<View style={styles.container}>
<TextInput
style={styles.textInput}
value={text}
onChangeText={setText}
placeholder="Placeholder"
placeholderTextColor="gray"
textAlign="right" // This affects both input text and placeholder
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
paddingHorizontal: 10,
paddingVertical: 5,
borderColor: 'gray',
borderWidth: 1,
borderRadius: 5,
},
textInput: {
fontSize: 16,
},
});
export default MyComponent;
How can I achieve the desired effect of aligning the input text to the right while keeping the placeholder text aligned to the left?
Any help would be greatly appreciated. Thank you!
2
Answers
I actually don’t know, if there is any native way to style the placeholder differently in React Native. But since you update the State, as soon as text is entered, you can react on that and change the alignment:
In terms of styling in react-native it’s similar to React per se, I believe what you are trying to achieve is something like this:
and the styles will be like this:
You can use the Text and make it as the placeholder of the TextInput and just manipulate the style.