Ad

Unexpected Behaviour On Removing Tag's Texts

- 1 answer

In my project I have used react-native-tags to get the different variants of colour from the user.

Here is the code :

<View style={{ marginVertical: 10, marginLeft: 20, justifyContent: 'center' }}>
    <MText size={18}>Colors</MText>
</View>
<Tags
    initialText=""
    textInputProps={{
        placeholder: "Enter Color",
        blurOnSubmit:false
    }}
    initialTags={this.state.colors}
    createTagOnString={[","]}
    createTagOnReturn={true}
    onChangeTags={(tags) => {
        this.setState((prevState) => ({
            colors: tags
        }), () => this.handleVariantChanges());
    }}
    onTagPress={(index, tagLabel, event, deleted) => console.log(index, tagLabel, event, deleted ? "deleted" : "not deleted")
    }
    containerStyle={styles.tagContainer}
    inputStyle={{ backgroundColor: "white" }}
    renderTag={({ tag, index, onPress, deleteTagOnPress, readonly }) => (
        <TouchableOpacity style={styles.tag} onPress={onPress} key={index.toString()}>
            <Icon name="times" color="#aaa" />
            <MText>{' '}{tag}</MText>
        </TouchableOpacity>
    )}
/>

Now, after running project I added some tags. Tags is added successfully. Then I continue to add another tags but spelling is not right so I removed till first character, but previous tags also removed automatically.

Another problem is that If I want to remove tag after adding some tags I am not able to remove that tag.

Here is problem gif :

enter image description here

Please help me what's going wrong here !!!

Note : This issue only happens if I use state value as an initialTags. If I keep initialTags as a blank array then everything working properly.

Ad

Answer

The issue is how react and react native tag works. Lets say you have two tags and you are entering text. When you hit backspaces delete the first character of the text that is not a tag yet, it automatically pops the second tag from the array. Since you are setting the state, the component is re-rendered and that removes the tag entirely.

You can fix this by using shouldComponentUpdate and returning false

shouldComponentUpdate(nextProps, nextState) {
   return false;
 }

What I would recommend is having a separate component for the tags and use that in your form and have a callback that updates the form when onChangeTags is triggered.

Ad
source: stackoverflow.com
Ad