How to Add an Icon inside TextInput in React Native

Last Updated on December 10, 2020.

Sometimes, you may want to show icon inside your TextInput, specifically saying- an icon aligned to the left of the TextInput. React Native TextInput has inlineImageLeft prop to add icon inside it. Unfortunately inlineImageLeft supports only Android platform.

There’s also another prop named inlineImagePadding to adjust the padding of the image inside TextInput. As the inlineImageLeft works natively, you have to add the image inside /android/app/src/main/res/drawable folder. Then you have to call the name of image as the reference.

In the example below, I have placed an image named ‘username’ inside /android/app/src/main/res/drawable. Then I called it as a reference. Once you made this change, you need to execute react-native run-android to see the changes in your project. For more details, you can look into the official doc.

Here’s the example code:

Class based component

import React, { Component } from 'react';
import { View, Text,TextInput} from 'react-native';

export default class componentName extends Component {
  constructor(props) {
    super(props);
    this.state = { text: '' };
  }

  render() {
    return (
      <View style={{flex: 1, justifyContent:'center', alignItems:'center'}}>
        <Text style={{margin: 10}}>TextInput with icon</Text>
        <TextInput
        style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        inlineImageLeft='username'
        inlineImagePadding={2}
        underlineColorAndroid= 'transparent'
        value={this.state.text}
      />
        
      </View>
    );
  }
}

Function based component

import React, {useState} from 'react';
import {View, Text, TextInput} from 'react-native';

const Home = () => {
  const [input, setInput] = useState('');
  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Text style={{margin: 10}}>TextInput with icon</Text>
      <TextInput
        style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => setInput(text)}
        inlineImageLeft="username"
        inlineImagePadding={2}
        underlineColorAndroid="transparent"
        value={input}
      />
    </View>
  );
};

export default Home;

Here’s the output:

icon inside TextInput React Native

I hope this tutorial will be helpful for you.

Leave a Reply

%d bloggers like this: