How to center and align text and placeholder in React Native search bar

46 Views Asked by At

I'm working on a search bar component in React Native and struggling to center and align the text and placeholder properly. Here are the issues I'm facing along with screenshots:

  1. The text and placeholder are not aligned properly within the search bar. https://i.stack.imgur.com/hvLy4.png

  2. The placeholder text also appears to be off-center. https://i.stack.imgur.com/zJEHZ.png

Below is the code for my search bar component:

import React from "react";
import { StyleSheet, TextInput, View, Keyboard, Text } from "react-native";
import tw from "twrnc"; // Import TWRNC library
import { Feather, Entypo } from "@expo/vector-icons";
import { TouchableOpacity } from "react-native";

const SearchBar = ({ clicked, searchPhrase, setSearchPhrase, setClicked }) => {
    return (
        <View style={tw`p-2 flex-row bg-gray-200 rounded-md items-center`}>
            {/* Search Icon */}
            <Feather name="search" size={20} color="black" style={tw`ml-1`} />
            {/* Input field */}
            <TextInput
                style={tw`flex-1 ml-2 text-lg justify-start items-start text-left`}
                placeholder="Search"
                value={searchPhrase}
                onChangeText={setSearchPhrase}
                onFocus={() => {
                    setClicked(true);
                }}
            />
            {/* Cancel button, depending on whether the search bar is clicked or not */}
            {clicked && (
                <TouchableOpacity
                    onPress={() => {
                        Keyboard.dismiss();
                        setClicked(false);
                        setSearchPhrase(""); // Clear the search phrase
                    }}
                >
                    <Text style={tw`text-blue-500 text-center pr-2 text-lg`}>
                        Cancel
                    </Text>
                </TouchableOpacity>
            )}
        </View>
    );
};

export default SearchBar;

I've attempted to adjust the styling of the main View, but it resulted in the search bar becoming smaller.

How can I properly center and align the text and placeholder within the search bar while ensuring it retains its size?

0

There are 0 best solutions below