Skip to content

Instantly share code, notes, and snippets.

@jakemmarsh
Created February 19, 2015 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakemmarsh/d7b8f564df923446886b to your computer and use it in GitHub Desktop.
Save jakemmarsh/d7b8f564df923446886b to your computer and use it in GitHub Desktop.
bootstrap-tokenfield
div.tokenfield {
display: block;
width: 100%;
height: 45px;
min-height: 2.5rem;
padding: 0 0.5rem;
vertical-align: middle;
background-color: $white;
.token-input {
position: relative;
display: inline-block;
width: 60px;
min-width: 60px;
height: 24px;
padding: 0;
top: 10px;
border: 0;
outline: none;
}
.token {
display: inline-block;
white-space: nowrap;
margin: 10px 5px 5px 0;
height: 26px;
vertical-align: top;
cursor: default;
background: $blue;
color: $white;
span.token-label {
padding-left: 5px;
}
a.close {
margin-left: 5px;
padding-right: 5px;
color: $white;
}
}
}
/**
* @jsx React.DOM
*/
'use strict';
var React = require('react/addons');
var _ = require('lodash');
var $ = require('jquery');
var tokenfield = require('bootstrap-tokenfield')($);
var TagInput = React.createClass({
propTypes: {
placeholder: React.PropTypes.string,
limit: React.PropTypes.number,
addTag: React.PropTypes.func,
removeTag: React.PropTypes.func
},
getDefaultProps: function() {
return {
limit: 3,
addTag: function() {},
removeTag: function() {}
};
},
componentDidMount: function() {
var $input = $(this.getDOMNode());
var isDuplicate = false;
$input.tokenfield({
limit: this.props.limit
});
// Prevent duplicate tags
$input.on('tokenfield:createtoken', function (evt) {
_.each(this.getTokens(), function(token) {
if ( token === evt.attrs.value ) {
evt.preventDefault();
isDuplicate = true;
}
});
if ( !isDuplicate ) { this.props.addTag(evt.attrs.value); }
}.bind(this));
// Update parent state accordingly when a token is removed
$input.on('tokenfield:removetoken', function(evt) {
this.props.removeTag(evt.attrs.value);
}.bind(this));
},
getTokens: function() {
return _.map($(this.getDOMNode()).tokenfield('getTokens'), function(token) {
return token.value;
});
},
render: function() {
return (
<input type="text" placeholder={this.props.placeholder} />
);
}
});
module.exports = React.createFactory(TagInput);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment