skip to Main Content

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


  1. 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:

    textAlign={text.length > 0 ? "right" : "left"}
    
    Login or Signup to reply.
  2. 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:

     return (
    <View style={styles.container}>
      <View style={styles.textInputContainer}>
        <TextInput
          style={styles.input}
          value={inputValue}
          onChangeText={text => setText(text)}
        />
      
          <Text style={styles.placeholder}>Placeholder</Text>
        
      </View>
    </View>
    );
    

    and the styles will be like this:

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
      textInputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: 'gray',
        borderRadius: 5,
        padding: 10,
      },
      placeholder: {
        position: 'absolute',
        right: 15,
        color: 'gray',
      },
      input: {
        flex: 1,
      },
    })

    You can use the Text and make it as the placeholder of the TextInput and just manipulate the style.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search