Open In App

How to Add Tag Input in React Native ?

Last Updated : 19 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Tags are widely used for managing items or categories in UI. Adding a tag input feature in React Native allows users to dynamically add and remove tags, enhancing data organization and filtering in applications. In this article, we will see how we can add tag input in react native application.

We are going to create a dynamic tag input component in React Native that allows users to add, edit, and remove tags. We are focusing in creating an intuitive and visually appealing interface for efficient tag management within our app.

Prerequisites:

Setting up React Native Project:

Step 1: Set Up the Development Environment

Install Expo CLI globally by running this command:

npm install -g expo-cli​

Step 2: Create React Native Application With Expo CLI

Create a new native project with Expo CLI by using this command:

expo init tag-input

Step 3: ​Navigate to project directory by using this command:

cd tag-input​

Project Structure:

React-Native-Project-Structure.png

Approach:

In this approach, we will first create a TagInput component to handle the tags input and then manage state variables for tags and input text. Then, we finally integrate TagInput component into the screen or application.

Example:

App.js file

Javascript




import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, 
    StyleSheet } from 'react-native';
  
const TagInputComponent = () => {
    const [tags, setTags] = useState([]);
    const [text, setText] = useState('');
    const [editIndex, setEditIndex] = useState(null);
  
    const addTag = () => {
        if (text.trim() !== '') {
            if (editIndex !== null) {
  
                // If editing an existing tag
                const newTags = [...tags];
                newTags[editIndex] = text.trim();
                setTags(newTags);
                setEditIndex(null);
            } else {
  
                // If adding a new tag
                setTags([...tags, text.trim()]);
            }
            setText('');
        }
    };
  
    const removeTag = (index) => {
        const newTags = [...tags];
        newTags.splice(index, 1);
        setTags(newTags);
    };
  
    const editTag = (index) => {
        const tagToEdit = tags[index];
        setText(tagToEdit);
        setEditIndex(index);
    };
  
    return (
        <View style={styles.container}>
            <View style={styles.tagContainer}>
                {tags.map((tag, index) => (
                    <View key={index} 
                        style={styles.tagWrapper}>
                        <TouchableOpacity 
                            onPress={() => editTag(index)} 
                            style={styles.tag}>
                            <Text style={styles.tagText}>
                                {tag}
                            </Text>
                        </TouchableOpacity>
                        <TouchableOpacity 
                            onPress={() => removeTag(index)} 
                            style={styles.removeButton}>
                            <Text style={styles.removeButtonText}>
                                X
                            </Text>
                        </TouchableOpacity>
                    </View>
                ))}
            </View>
            <View style={styles.inputContainer}>
                <TextInput
                    style={styles.input}
                    placeholder="Add a tag"
                    value={text}
                    onChangeText={setText}
                    onSubmitEditing={addTag}
                />
                <TouchableOpacity onPress={addTag} 
                    style={styles.addButton}>
                    <Text style={styles.buttonText}>
                        {editIndex !== null ? 'Update' : 'Add'}
                    </Text>
                </TouchableOpacity>
            </View>
        </View>
    );
};
  
const App = () => {
    return (
        <View style={styles.appContainer}>
            <TagInputComponent />
        </View>
    );
};
  
const styles = StyleSheet.create({
    appContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 20,
        backgroundColor: '#F5F5F5',
    },
    container: {
        width: '100%',
        paddingHorizontal: 20,
    },
    tagContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginBottom: 10,
    },
    tagWrapper: {
        flexDirection: 'row',
        alignItems: 'center',
        marginVertical: 5,
        marginRight: 5,
    },
    tag: {
        backgroundColor: '#ccc',
        borderRadius: 20,
        paddingHorizontal: 10,
        paddingVertical: 5,
    },
    tagText: {
        color: 'black',
        fontWeight: 'bold',
        fontSize: 17,
    },
    removeButton: {
        marginLeft: 5,
        padding: 5,
        borderRadius: 10,
        backgroundColor: '#E53935',
    },
    removeButtonText: {
        color: '#FFFFFF',
        fontSize: 18,
    },
    inputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    input: {
        flex: 1,
        height: 40,
        borderColor: '#CCCCCC',
        borderWidth: 1,
        paddingHorizontal: 10,
        borderRadius: 5,
        marginRight: 10,
        backgroundColor: '#FFFFFF',
    },
    addButton: {
        backgroundColor: '#4CAF50',
        paddingHorizontal: 15,
        paddingVertical: 10,
        borderRadius: 5,
    },
    buttonText: {
        color: '#FFFFFF',
        fontSize: 16,
        fontWeight: 'bold',
    },
});
  
export default App;


Explanation:

  • Import necessary React and React Native dependencies.
  • Define the TagInputComponent function component to manage tags, text input, and edited tag index.
  • Implement addTag function to add new tags or update existing tags.
  • Create removeTag function to remove tags based on their index.
  • Implement editTag functi​on to enable editing of existing tags.
  • Define component rendering logic using React Native components and styles.
  • Use TagInputComponent within the root App component.
  • Define custom styles using StyleSheet.create method.

Start the React Native Application:

Run the following command:

To run on Expo:

npx expo start

To run on Android:

npx react-native run-android

To run on iOS:

npx react-native run-ios

Output:

How-to-Add-Tag-Input-in-React-Native.gif



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads