React Material-UI Tags Input control
npm install react-materialui-tagsReact Material-UI Tags
===
React Material-UI Tags is a simple tagging component ready to drop in your React projects. Originally based on the React Tags project by Prakhar Srivastav this version removes the drag-and-drop re-ordering functionality,
npm install --save react-tag-input
`
make sure you have installed the peer dependencies as well with below versions
`
react: ^16.3.1,
react-dnd: ^5.0.0
react-dnd-html5-backend: ^3.0.2
react-dom": ^16.3.1
`
It is, however, also available to be used separately (dist/ReactTags.min.js). If you prefer this method remember to include ReactDND as a dependancy. Refer to the example to see how this works.
$3
Here's a sample implementation that initializes the component with a list of initial tags and suggestions list. Apart from this, there are multiple events, handlers for which need to be set. For more details, go through the API.
`javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { WithContext as ReactTags } from 'react-tag-input';
const KeyCodes = {
comma: 188,
enter: 13,
};
const delimiters = [KeyCodes.comma, KeyCodes.enter];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
tags: [
{ id: "Thailand", text: "Thailand" },
{ id: "India", text: "India" }
],
suggestions: [
{ id: 'USA', text: 'USA' },
{ id: 'Germany', text: 'Germany' },
{ id: 'Austria', text: 'Austria' },
{ id: 'Costa Rica', text: 'Costa Rica' },
{ id: 'Sri Lanka', text: 'Sri Lanka' },
{ id: 'Thailand', text: 'Thailand' }
]
};
this.handleDelete = this.handleDelete.bind(this);
this.handleAddition = this.handleAddition.bind(this);
this.handleDrag = this.handleDrag.bind(this);
}
handleDelete(i) {
const { tags } = this.state;
this.setState({
tags: tags.filter((tag, index) => index !== i),
});
}
handleAddition(tag) {
this.setState(state => ({ tags: [...state.tags, tag] }));
}
handleDrag(tag, currPos, newPos) {
const tags = [...this.state.tags];
const newTags = tags.slice();
newTags.splice(currPos, 1);
newTags.splice(newPos, 0, tag);
// re-render
this.setState({ tags: newTags });
}
render() {
const { tags, suggestions } = this.state;
return (
suggestions={suggestions}
handleDelete={this.handleDelete}
handleAddition={this.handleAddition}
handleDrag={this.handleDrag}
delimiters={delimiters} />
)
}
};
ReactDOM.render( , document.getElementById('app'));
`
A note about Contexts
One of the dependencies of this component is the react-dnd library. Since the 1.0 version, the original author has changed the API and requires the application using any draggable components to have a top-level backend context. So if you're using this component in an existing Application that uses React-DND you will already have a backend defined, in which case, you should require the component without the context.
`javascript
const ReactTags = require('react-tag-input').WithOutContext;
`
Otherwise, you can simply import along with the backend itself (as shown above). If you have ideas to make this API better, I'd love to hear.
$3
Option | Type | Default | Description
--- | --- | --- | ---
|tags | Array | [] | An array of tags that are displayed as pre-selected
|suggestions | Array | [] | An array of suggestions that are used as basis for showing suggestions
|delimiters | Array | [ENTER, TAB] | Specifies which characters should terminate tags input
|placeholder | String | Add new tag | The placeholder shown for the input
|labelField | String | text | Provide an alternative label property for the tags
|handleAddition | Function | undefined | Function called when the user wants to add a tag (required)
|handleDelete | Function | undefined | Function called when the user wants to delete a tag (required)
|handleDrag | Function | undefined | Function called when the user drags a tag
|handleFilterSuggestions | Function | undefined | Function called when filtering suggestions
|handleTagClick | Function | undefined | Function called when the user wants to know which tag was clicked
|autofocus | Boolean | true | Boolean value to control whether the text-input should be autofocused on mount
|allowDeleteFromEmptyInput | Boolean | true | Boolean value to control whether tags should be deleted when the 'Delete' key is pressed in an empty Input Box
|handleInputChange | Function | undefined | Event handler for input onChange
|handleInputFocus | Function | undefined | Event handler for input onFocus
|handleInputBlur | Function | undefined | Event handler for input onBlur
|minQueryLength | Number | 2 | How many characters are needed for suggestions to appear
|removeComponent | Boolean | false | Custom delete/remove tag element
|autocomplete | Boolean/Number | false | Ensure the first matching suggestion is automatically converted to a tag when a delimiter key is pressed
|readOnly | Boolean | false | Read-only mode without the input box and removeComponent and drag-n-drop features disabled
|name | String | undefined | The name attribute added to the input
|id | String | undefined | The id attribute added to the input
|maxLength | Number | Infinity | The maxLength attribute added to the input
|inline | Boolean | true | Render input field and selected tags in-line
|inputFieldPosition | String | inline | Specify position of input field relative to tags
|allowUnique | Boolean | true | Boolean value to control whether tags should be unqiue
|allowDragDrop | Boolean | true | Boolean value to control whether tags should have drag-n-drop features enabled
|renderSuggestion | Function | undefined | Render prop for rendering your own suggestions
##### tags (optional, defaults to [])
An array of tags that are displayed as pre-selected. Each tag should have an id property, property for the label, which is specified by the labelField and class for label, which is specified by className.
`js
// With default labelField
const tags = [ { id: "1", text: "Apples" } ]
// With labelField of name
const tags = [ { id: "1", name: "Apples" } ]
// With className
const tags = [ { id: "1", text: "Apples", className: 'red'} ]
`
##### suggestions (optional, defaults to [])
An array of suggestions that are used as basis for showing suggestions. These objects should follow the same structure as the tags. So if the labelField is name, the following would work:
`js
// With labelField of name
const suggestions = [
{ id: "1", name: "mango" },
{ id: "2", name: "pineapple"},
{ id: "3", name: "orange" },
{ id: "4", name: "pear" }
];
##### delimiters (optional, defaults to [ENTER, TAB])
Specifies which characters should terminate tags input. An array of character codes.
`js
const Keys = {
TAB: 9,
SPACE: 32,
COMMA: 188,
};
delimiters={[Keys.TAB, Keys.SPACE, Keys.COMMA]}
/>
`
##### placeholder (optional, defaults to Add new tag)
The placeholder shown for the input.
`js
let placeholder = "Add new country"
`
##### labelField (optional, defaults to text)
Provide an alternative label property for the tags.
`jsx
tags={tags}
suggestions={}
labelField={'name'}
handleDrag={}
/>
`
This is useful if your data uses the text property for something else.
##### handleAddition (required)
Function called when the user wants to add a tag (either a click, a tab press or carriage return)
`js
function(tag) {
// add the tag to the tag list
}
`
##### handleDelete (required)
Function called when the user wants to delete a tag
`js
function(i) {
// delete the tag at index i
}
`
##### handleDrag (optional)
If you want tags to be draggable, you need to provide this function.
Function called when the user drags a tag.
`js
function(tag, currPos, newPos) {
// remove tag from currPos and add in newPos
}
`
##### handleFilterSuggestions (optional)
To assert control over the suggestions filter, you may contribute a function that is executed whenever a filtered set
of suggestions is expected. By default, the text input value will be matched against each suggestion, and [those that
start with the entered text][default-suggestions-filter-logic] will be included in the filters suggestions list. If you do contribute a custom filter
function, you must return an array of suggestions. Please do not mutate the passed suggestions array.
For example, if you prefer to override the default filter behavior and instead match any suggestions that contain
the entered text _anywhere_ in the suggestion, your handleFilterSuggestions property may look like this:
`js
function(textInputValue, possibleSuggestionsArray) {
var lowerCaseQuery = textInputValue.toLowerCase()
return possibleSuggestionsArray.filter(function(suggestion) {
return suggestion.toLowerCase().includes(lowerCaseQuery)
})
}
`
Note: The above custom filter uses String.prototype.includes, which was added to JavaScript as part of the ECMAScript 7
specification. If you need to support a browser that does not yet include support for this method, you will need to
either refactor the above filter based on the capabilities of your supported browsers, or import a [polyfill for
String.prototype.includes][includes-polyfill].
##### handleTagClick (optional)
Function called when the user wants to know which tag was clicked
`js
function(i) {
// use the tag details at index i
}
`
##### autofocus (optional, defaults to true)
Optional boolean param to control whether the text-input should be autofocused on mount.
`jsx
autofocus={false}
...>
`
##### allowDeleteFromEmptyInput (optional, defaults to true)
Optional boolean param to control whether tags should be deleted when the 'Delete' key is pressed in an empty Input Box.
`js
allowDeleteFromEmptyInput={false}
...>
`
##### handleInputChange (optional)
Optional event handler for input onChange
`js
handleInputChange={this.handleInputChange}
...>
`
##### handleInputFocus (optional)
Optional event handler for input onFocus
`js
handleInputFocus={this.handleInputFocus}
...>
`
##### handleInputBlur (optional)
Optional event handler for input onBlur
`js
handleInputBlur={this.handleInputBlur}
...>
`
##### minQueryLength (optional, defaults to 2)
How many characters are needed for suggestions to appear.
##### removeComponent (optional)
If you'd like to supply your own tag delete/remove element, create a React component and pass it as a property to ReactTags using the removeComponent option. By default, a simple anchor link with an "x" text node as its only child is rendered, but if you'd like to, say, replace this with a