Code Monkey home page Code Monkey logo

react-native-tags's Introduction

React-Native-Tags

Build Status npm npm version

A React Native component that allows you to input text and formats the text into a tag when a space or comma is entered. Tapping on the tag will remove it.

Demo

Installation

npm install --save react-native-tags
yarn add react-native-tags

Usage

import React from "react";
import { TouchableOpacity, Text } from "react-native";
import Tags from "react-native-tags";

const MyTagInput = () => (
  <Tags
    initialText="monkey"
    textInputProps={{
      placeholder: "Any type of animal"
    }}
    initialTags={["dog", "cat", "chicken"]}
    onChangeTags={tags => console.log(tags)}
    onTagPress={(index, tagLabel, event, deleted) =>
      console.log(index, tagLabel, event, deleted ? "deleted" : "not deleted")
    }
    containerStyle={{ justifyContent: "center" }}
    inputStyle={{ backgroundColor: "white" }}
    renderTag={({ tag, index, onPress, deleteTagOnPress, readonly }) => (
      <TouchableOpacity key={`${tag}-${index}`} onPress={onPress}>
        <Text>{tag}</Text>
      </TouchableOpacity>
    )}
  />
);

Render Props

renderTag

If you would like to add new functionality or modify the way that the tags are rendered then pass in a renderTag prop.

PropName Description
tag text of the tag
index position in the array of tags
onPress Removes the tag if deleteTagsOnPress and readonly is false

Props

PropName Description Default
initialText The input element's text
textInputProps forward props to the textInput
initialTags ['the', 'initial', 'tags']
createTagOnString Triggers new tag creation [",", ".", " "]
onChangeTags Fires when tags are added or removed
maxNumberOfTags The max number of tags that can be entered infinity
onTagPress Fires when tags are pressed
readonly Tags cannot be modified false
deleteTagOnPress Remove the tag when pressed true
renderTag Manage the rendering of your own Tag

Style modification props

PropName Description Default
style Style (containerStyle alias)
containerStyle Style
inputContainerStyle Style
inputStyle Style
tagContainerStyle Style
tagTextStyle Style

react-native-tags's People

Contributors

btuck044 avatar dajaffe avatar havens avatar peterp avatar wewishyouhappiness avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-native-tags's Issues

Synthetic event warning

you get “Warning: This synthetic event is reused for performance reasons” when you touch and delete the tags. event.persist() solves it.

Cheers.

How to access tags via this.state

What is the correct usage of the onChangeTags method, the documentation isn't quite clear as it keeps resetting the tags - is there not an internal array of the component that can be exposed?

undefined is not an object (evaluating 'event.persist')

Hello,
I'm trying to add simple tags to my app. But I have a problem in onPress handler when I'm trying to delete pressed tag.

here's my code

<Tags
  textInputProps={{
    placeholder: "describe your tags here"
  }}
  onChangeTags={tags => setTags(tags)}
  onTagPress={(index, tagLabel, event, deleted) =>
    console.log(index, tagLabel, event, deleted ? "deleted" : "not deleted")
  }
  containerStyle={{ justifyContent: 'center' }}
  inputStyle={{ backgroundColor: '#F4E4E4' }}
  renderTag={({ tag, index, deleteTagOnPress, onPress }) => (
    <TouchableOpacity key={`${tag}-${index}`} onPress={onPress} style={styles.tags}>
      <Text style={styles.textTags}>{tag}</Text>
    </TouchableOpacity>
  )}
/>

Expected Behaviour
Tag that pressed should be deleted

Actual Behavior
I got an error

undefined is not an object (evaluating 'event.persist')

But, when I try open react-native-tags in node_modules and delete/comment the line where the event.persist(); in index.js file, everything works fine.

What should I do beside changing the code in the node_modules to get everything works fine

I have also tried
onPress={(e) => onPress(e)}
onPress={() => onPress()}
but still not working

Thanks

Warning: componentWillReceiveProps has been renamed

Hi!

Thanks for your great component! Do you think would be possible for you do that quick update?

:)

Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.

* Move data fetching code or side effects to componentDidUpdate.
* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

Please update the following components: Tags
- node_modules/expo/build/environment/muteWarnings.fx.js:18:23 in warn
* App.js:24:14 in console.warn
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5864:19 in printWarning
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5892:25 in lowPriorityWarning
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:6135:8 in ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:20377:6 in flushRenderPhaseStrictModeWarningsInDEV
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19606:41 in commitRootImpl
* [native code]:null in commitRootImpl
- node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19590:4 in commitRoot
* [native code]:null in commitRoot
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18709:28 in runRootCallback
* [native code]:null in runRootCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5642:32 in runWithPriority$argument_1
- node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5638:22 in flushSyncCallbackQueueImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5627:28 in flushSyncCallbackQueue
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18796:28 in batchedUpdates$1
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:2709:30 in batchedUpdates
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:2794:17 in batchedUpdates$argument_0
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:2870:28 in receiveTouches
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

Suggestion: Support style classes defined in StyleSheet.create()

The attribute values for the styles only accept a style object, they do not support the adding of styles from StyleSheet.create().

I have to use;

tagTextStyle={{ color: '#fff', fontWeight: 'bold',fontSize: 12 }}

whereas I would prefer to use

tagTextStyle={styles.tagText}

I think this is a reversion from an earlier version of react-native-tags, as the styles.tagText would be loaded in as id reference to the style, not the styles object, so this throws warnings in the App.

Many thanks

Unexpected behaviour on removing tag's text.

In my project I have used this library to get the different variants of color 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 :

ezgif com-video-to-gif

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

.d.ts file is missing

The file .d.ts is not present in the package as result, the warning bellows keeps showing.

Could not find a declaration file for module 'react-native-tags'. '.../node_modules/react-native-tags/index.js' implicitly has an 'any' type.
Try npm install @types/react-native-tags if it exists or add a new declaration (.d.ts) file containing declare module 'react-native-tags';ts(7016)

Remove text Input.

Hi
thanks for a great library. Can we remove text input? Only show tags generated by some other mechanism.

Thanks

tags not saving

When i press done on the keyboard the tags are deleted ...
and how can I write the tags under the text input without changing the size of the text input?

Re-rendering view on initial tags change

Hey @peterp, first of all, awesome library 🙌

Maybe what I'm doing is out of the scope of this project. I've basically built a wrapper that the user can select/deselect a tag between a list of tags. Similar to setting your interests in various apps. Everything works perfectly apart from re-rendering the view on the initialTags prop change. I had a look at your code and it seems that it's like that by design.

I've solved my issue by re-setting the state tags when the props tags change.

componentDidUpdate(prevProps) {
    if (JSON.stringify(prevProps.initialTags) !== JSON.stringify(this.props.initialTags)) {
      this.setState({ tags: [...this.props.initialTags] });
    }
}

Is there another way to re-render the view?

TextField not displaying placeholder value

showLastTag function prevent placeholder from displaying on the input field. This is because the initial value of text in state is set to a whitespace instead of an empty string.

showLastTag = () => {
    this.setState(state =>
      ({
        tags: state.tags.slice(0, -1),
        text: state.tags.slice(-1)[0] || " "
      }),
      () =>
        this.props.onChangeTags && this.props.onChangeTags(this.state.tags)
    );
  };

Unable to show updated value.

Hi @peterp

I have integrated this library and it is really great library.

I have only one issue and that is I want to make value in 000 - 000 - 0000 format. I have implement the function for the same as well but don't know how to update the state and which prop is used to display the updated value.

For example :-

onChangeTags={tags => this.props.formatPhone(tags)}

formatPhone is a function which return number value to 000 - 000 - 0000 format but it should not reflect the same in the input field.

Please help!

Thanks
Regards

Lovedeep Singh

unable to use react-native-tags with Formik

Update: After struggling for 2 days and posting this issue, I've finally got the solution. I have to put following code on my onChangeTags.
formikProps.setFieldValue("careers",careers)

So my problem has nothing to do with this package.
Sorry to bother. Maintainers can delete this issue.

=========================================================================================

Hi,
Not sure if this is the problem with Formik or not. In "onChangeTags" when I use "formikProps.handleChange(key)", it seems that formik is unable to see the changes.
Here is the code

`<Formik
initialValues={{careers:[]}}
onSubmit={(values,action)=>{
action.setSubmitting(true)
}}
>
{(formikProps)=>(


Creers (press space after adding a career)

<Tags
initialTags={formikProps.values["careers"]}

        onChangeTags={(careers)=>{
            formikProps.handleChange('careers')  // ==> This should work here. But it doesn't work.
        }}
        onTagPress={(index,tagLabel,event,deleted)=>console.log(index,tagLabel,event, deleted?"deleted":"not deleted")}
        inputStyle={{
            borderBottomColor:borderColor,
            borderBottomWidth:1,
            borderRadius:0,
            backgroundColor:"white",
            color:Colors.darkGrey,
            fontSize:Fonts.size.body,
            fontFamily:Fonts.type.base,
            lineHeight:17,
            paddingLeft:0,
        }}
        tagTextStyle={styles.label}
        renderTag={({tag,index, onPress, deleteTagOnPress, readonly})=>(
            <TouchableOpacity style={{
                borderWidth:1,
                borderColor:"#18B18D",
                borderRadius:4,
                marginVertical:3
            }}
            key={`${tag}-${index}`}
            onPress={onPress}
            // onChangeText={formikProps.handleChange(formikKey)}
            >
                <View style={{padding:10}}>
                    <Text fwBold caption primaryColor>
                        {tag}
                    </Text>
                </View>

            </TouchableOpacity>
        )}

        />
      </View
  )}

`

Adding a X at the end of each tag also i can't add a placeholder

  • Can you kindly add X at the end of each tag i added after importing your library but it will be great if you can add a default X at the end of each tab it will be great in visualizing
  • i added place holder but it's not visible but when i press backspace on empty tag input it show's place holder for a sec and disappears after a millisecond

In active development?

Hello,

I am using Expo 28 and React 16.3.1 and I get errors about legacy methods being used in is there any plan to remove componentWillRecieveProps and issue an updated version?

Would be cool if you could provide a method to auto remove the tag from an array if an x icon is clicked, but I would only look into these if your component will continue to be worked on.

Looks great though, so please let me know!

Regards

Please update the description

There's one issue in the description.
Please change props name from deleteTagOnPress to deleteOnTagPress in the description.
Or maybe change the props name in the code base from deleteOnTagPress to deleteTagOnPress

Initial Tags are not getting set

I am having problems setting my initial tags with the code below. Is there something obvious that I am doing wrong?

import React, {useEffect, useState} from 'react';
import {
  TouchableOpacity, Text
} from 'react-native';
import Tags from "react-native-tags";

function JobScreen({ route, navigation }) {
  const [niche, setNiche] = useState(['tag1', 'tag2'])

  return (
         <Tags
            textInputProps={{placeholder: "E.g - Fashion"}}
            maxNumberOfTags={10}
            initialTags={niche}
            onChangeTags={niches => setNiche(niches)}
            containerStyle={{ borderColor: '#E0E0E0', borderWidth: 1, marginVertical: 4, borderRadius: 8, paddingTop: 4 }}
            inputStyle={{ backgroundColor: "white" }}
            renderTag={({ tag, index, onPress, deleteTagOnPress, readonly }) => (
              <TouchableOpacity key={`${tag}-${index}`} onPress={onPress}>
                <Text style={{ marginTop: 2, marginBottom: 2, color: "#7A7A7A", marginLeft: 5, paddingVertical: 5, paddingHorizontal: 10,
                               borderColor: "#7A7A7A", borderWidth: 2, borderRadius: 15 }}>{tag}</Text>
              </TouchableOpacity>
            )}
          />
 )
}

renderTextinput method

Hello,
would it be possible to isolate the Textinput in its own render method so we may override it?
A use case I've encountered recently is having to use a Mask (Either this or this) which would require me to override the default Input.

Thank you.

Position of the the tags list isn't changeable.

The tag list appears before the input therefore new tags move the position of the input.
Styling isn't possible because the list of tags doesn't have a container.

Either a separate container or an option to change the position (above or below) of the tags list would be nice.

Having tags in TextInput

Hello,

Is there a way to get the tags button inside the TextInput like in gmail ?

Thank you !

Unable to set placeholder without setting initialText to ""

Hello,
Currently it is not possible to have a placeholder without setting the initialText prop to "". It is because you set the textInput value to " " (with a space) by default.

In the same way it is not possible to get the placeholder back after removing all tags.

The library doesn't support to update the tags in the input box if I pass tags as props or mutate those tags

Currently, the library supports only initialTags prop, The initial tags are functioning properly on the component mounting.

My usecase requires that, the tags should be shown to the input box both by typing manually and by sending them as props.

If you require more explanation of my usecase or anything else, let me know.

For this feature, I can also quickly create a pull request.

@peterp

not accepting initialTags, receiving undefined object

Using latest v1.0.0 after #7 fix

I'm receiving this ...
screen shot 2018-04-11 at 11 19 09 pm

When trying to assign an array to initialTags

<Tags  
  initialText=""  
  initialTags={data.keywords}   
  onChangeTags={tags => console.log(tags)}  
  onTagPress={(index, tagLabel, event) => console.log(index, tagLabel, event)}  
  inputStyle={{ backgroundColor: 'white' }}  
/>  

Note I was using the same initialTags prop in the previous version without any issue. The only thing updated (to match example doc) was the onChangeTags. #

Suggestion; Add `onFinish` prop.

When finishing adding tags, if the last one is not made a tag by a comma, space or something preferred, the one ends up not being a tag successfully.
So I suggest that you should add a prop called onFinish with a boolean argument to make the very last one a tag automatically.

Does it has IOS support?

Hi, I am asking here because didn't found any question-related at closed issues tab.

Thank you.

Screenshots Please

May you please add screenshots (ideally GIF) of this in action in repo? That's the first thing a lot of RN package searchers do. There are so many packages its not easy to install each one, render it respecting properties, then uninstall it if it doesn't fit.

initial text for each tags

Hello @peterp ,

I was wondering if there is feature for initial text for each tags. Because, in props initialText just affect on the first tag. So it would be nice if the initial text also implement on every tags.

For example I want user to automatically input tags with the first character is '#'.

I try to modified your library, just basically add a new props initialEachText and put it on

showLastTag = () => {
    this.setState(state =>
      ({
        tags: state.tags.slice(0, -1),
        text: state.tags.slice(-1)[0] || this.state.initialEachText
      }),
      () =>
        this.props.onChangeTags && this.props.onChangeTags(this.state.tags)
    );
  };

  addTag = text => {
    this.setState(state =>
      ({
        tags: [...state.tags, text.trim()],
        text: this.state.initialEachText
      }),
      () => this.props.onChangeTags && this.props.onChangeTags(this.state.tags)
    );
  };

Just changed the " " (space) to initialEachText that can be modified.

And I just set the props initialText={'#'} and initialEachText={'#'}.

This would be great if you considering to add this feature. Thank you 🤝

Typing tags doesn't support multibyte characters

When one types something not entirely ASCII as a tag content, for example "göteborg", the component distorts multibyte characters and enters "g;teborg" instead. I think it's due to the fact you're using slice() rather than substr() when working with strings internally.
I am pretty sure same result will be seen when entering tags in Chinese or Russian, for instance.

Support focus() event like a TextInput component

When creating references to allow the next keyboard to tab through TextInputs, the focus() call on the Tag field throws an exception. It would be great if support could be added.

The plugin I (obviously) think is great, it should probably become something part of Expo/React-Native as its far better than the others - so excuse my bug finding.

Placeholder Color

Hi, is there any way to change the color of the placeholder text?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.