Position Element on Top of Input Field

I'm struggling to position the Avatar element over my TextInput to create a traditional search bar appearance. However, the icon isn't overlapping the TextInput. Could you please explain why it's not working or suggest a more effective way to place the search icon above the TextInput? Thank you.

import { Avatar } from 'react-native-elements';
import FontAwesome from './node_modules/@expo/vector-icons/fonts/FontAwesome.ttf';
import MaterialIcons from './node_modules/@expo/vector-icons/fonts/MaterialIcons.ttf';

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {timePassed: false};
    }
    
    state = {
        fontLoaded: false
    };
    
    async componentWillMount() {
        try {
            await Font.loadAsync({
                FontAwesome,
                MaterialIcons
            });
            this.setState({ fontLoaded: true });
        } catch (error) {
            console.log('Error loading icon fonts', error);
        }
    }

    render() {
        setTimeout(() => {
            this.setState({timePassed: true})
        }, 4000);
        
        if (!this.state.timePassed) {
            return <Splash/>;
        } else {
            return (
                <View style={BackStyles.container}>
                    <Avatar style={BackStyles.searchIcon} icon={{ name: 'search', size: 25 }}/>
                    <TextInput placeholder="Search for your herbs.." underlineColorAndroid={'transparent'} style={BackStyles.textBox}/>
                </View>
            );
        }
    }
}

const BackStyles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        alignSelf: 'stretch',
        flex: 1,
        backgroundColor: '#E2E2E2',
        marginTop: 20,
    },
    textBox: {
        flex: 1,
        height: 45,
        padding: 4,
        paddingLeft: 20,
        flexGrow: 1,
        color: '#000',
        backgroundColor: '#fff',
    },
    searchIcon:{
        position: 'absolute',
        alignSelf: 'stretch',
        height: 45,
        flex: 1,
        top: 50,
        flexGrow: 1,
        padding: 4
    }
});

Answer №1

To align the TextInput to the left and the search icon to the right, you can utilize Flexbox's justifyContent property. By setting a border on the container instead of the TextInput, it creates the illusion that the search icon is attached to the input field, even though they are separate components.

// Custom styles
const customStyles = StyleSheet.create({
  searchContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: 'black',
  },
});

// Implementing the components
<View style={customStyles.searchContainer}>
  <TextInput ...props />
  <Avatar ...props />
</View>

If you're interested in delving deeper into the wonders of Flexbox and how it works, I highly recommend checking out Chris Coyier's informative Flexbox guide.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for me to utilize http/https proxies or am I restricted to only using socks5 for scraping wss/socket

Is it possible to utilize http/https scraping proxies for scraping socket.io/wss endpoints from a website? I am looking to protect my actual IP address and avoid getting blocked by the website. import io from 'socket.io-client' const socket = i ...

What is the best way to prompt users to submit comments with a popup textarea box?

Within my project, I have incorporated a dropdown list: <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select subject <span class="caret"></span> </but ...

Navigating Pre-Fetched Client Routes in Gatsby with @ReachRouter

Let's consider this scenario. Imagine a user enters /company/<company-id> in the address bar. Because the app is completely separate from the backend, it must prefetch the companies. The usual flow is /login -> /company/. Handling this sequ ...

The compatibility of this Module is not supported for win32 in react-native platform

Encountering an issue during the installation process: fsevents Unfortunately, this module is not compatible with win 32. ...

Replacing values between Arrays and Objects

I currently possess a lookupMap variable that contains an index of counties and their corresponding codes. Here is a snippet: { ANDERSON: { county: 'ANDERSON', code: 'us-tx-001' }, ANDREWS: { county: 'ANDREWS', code: ' ...

Integrating MongoDB data values with Node.js for enhanced functionality

Hey everyone, I'm looking to add two field values {type:Number} from a MongoDB collection using node js and then store the result back in the same collection. To achieve this, I have outlined the steps below: Retrieve the data value from MongoDB wit ...

Exploring the Interactive Possibilities of CSS3 with Background Tiles

I'm struggling to implement a flip effect where the content of a div changes, but I can't seem to prevent the text from disappearing after a few seconds. I've tried using backface-visibility:hidden with no luck! HTML <div class="cards" ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

Expanding the Width of Bootstrap 4 Dropdown Button

Currently, I am utilizing Bootstrap 4's dropdown feature. Is there a way to modify the code below so that the dropdown menu that appears upon clicking the button matches the same width as the button itself? It's important to note that the button ...

Continuously improving the form as they evolve

I am interested in creating a form that automatically sends data when users make changes to it. For instance: Imagine a scenario where a moderator is editing an article and changes values in a select field. As soon as the change is made, an ajax request ...

Guide for running an await function consecutively with JavaScript and React

I have the following code snippet: const somePromises = values.map(({variable, value}) => this.post('/api/values/', { variable, value, item: itemId, }) ); await Promise.all(somePromises); if (somecondition) { ...

HTML View of JSON Object Hierarchy

Hello, I have been trying various methods but am struggling to figure out how to display the following JSON object as a tree HTML view with ul li items using JavaScript. Can anyone help me with this? [ { "CategoriesModelId": 7, "Name": "Parent ...

Combining Content, Attr, and Url in a single statement

I've been utilizing the content attribute for quite some time now, but today I decided to explore something different. Instead of relying on JS to show an image tooltip, I was curious if it could be done dynamically using CSS. So I attempted the foll ...

What is the method to identify the key responsible for triggering a textbox input event?

Suppose there is a textbox on the webpage: <input id='Sub' type='text'> To capture each time the input changes, you can use the following code: sub = document.getElementById('Sub'); sub.addEventListener('input&a ...

What is the quickest way to increase value in the DOM?

Is there a more efficient method for incrementing a DOM value that you know of? let progress = +document.getElementById("progress").innerHTML; progress++; document.getElementById("progress").innerHTML = progress; Perhaps something like t ...

Standardize all values for each key in sub-dictionaries and include them as additional key-value pairs

Suppose there is a dictionary containing nested sub-dictionaries: let dict = { "SEATTLE" : { "gross_sales" : 106766, "price" : 584.50, "dates" : [ { " ...

Obtaining the Time Zone from an Area Code Using JavaScript

Can a Script in JavaScript Determine the Time Zone Based on Area Code? I possess the Area Codes of the User. ...

What is the best way to connect a router link and dialog box in a dropdown menu using Vue.js?

https://i.sstatic.net/JahMG.pngI am working on implementing a dropdown menu that includes a router link to another component and a dialog component for a dialog box. Here is the code snippet for reference: <td align="center"> <v-btn ...

What steps can I take to limit access to my API exclusively for the Frontend?

I'm in the process of creating a gaming platform, and unfortunately, there has been an exploitation of the API. How can I establish a set of "approved domains" that are allowed to access my API? The previous misuse of the API resulted in individuals ...

Despite seeming false, my Javascript if statement still evaluates to true

On my webpage, I have a button and a form. The intended functionality is for the button to display the form when clicked, and hide it when clicked again. The issue I'm facing is that no matter if the statement is true or false, the first if statement ...