DEV Community

Cover image for Implementing a Tag Feature with Suggestions Using React Tag Autocomplete
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Implementing a Tag Feature with Suggestions Using React Tag Autocomplete

This article was originally published on bmf-tech.com.

I was thinking of developing a tag feature from scratch, but I found many convenient React Components, so I decided to use them.

Environment

Introduction

Install React Tag Autocomplete using npm.

npm install --save react-tag-autocomplete

There are various ways to include it, but in this environment, we will use require.

var ReactTags = require('react-tag-autocomplete');
Enter fullscreen mode Exit fullscreen mode

Now we are ready.

Implementation

// Various parts omitted
<div id="react-tag-autocomplete"></div>
Enter fullscreen mode Exit fullscreen mode

There is a Usage section on github, but let's consider a case where we modify it a bit to fetch data by hitting an API. (Here, we use superagent.)

The API returns a JSON response like this:

[{"id":1,"name":"Programming"},{"id":2,"name":"Housework"},{"id":3,"name":"Home Security"},{"id":4,"name":"Early to Bed, Early to Rise"},{"id":5,"name":"Three-Day Monk"}]
Enter fullscreen mode Exit fullscreen mode

Debugging res.body.skills
Screenshot 2016-09-28 3.04.10.png

var ReactTags = require('react-tag-autocomplete');

var App = React.createClass({
  getInitialState: function () {
    return {
      tags: [],
      suggestions: []
    }
  },

  componentDidMount: function () {
    request
      .get('/api/v1/user/config')
      .end(function(err, res){
        if (err) {
          alert('Communication error. Please reload.');
        }
        this.setState({
          suggestions: res.body.skills
        });
      }.bind(this));
  },

  handleDelete: function (i) {
    var tags = this.state.tags
    tags.splice(i, 1)
    this.setState({ tags: tags })
  },![tags.gif](https://bmf-tech.com/assets/images/posts/react-tag-autocomplete-implementation/173c6de9-b87a-6200-65ed-506e181f565e.gif)
![tags.gif](https://bmf-tech.com/assets/images/posts/react-tag-autocomplete-implementation/a3372702-2a85-9b80-0b53-ede2c9c3c486.gif)


  handleAddition: function (tag) {
    var tags = this.state.tags
    tags.push(tag)
    this.setState({ tags: tags })
  },

  render: function () {
    return (
      <ReactTags
        tags={this.state.tags}
        suggestions={this.state.suggestions}
        handleDelete={this.handleDelete}
        handleAddition={this.handleAddition} />
    )
  }
})

ReactDOM.render(
  <App />, 
  document.getElementById('react-tag-autocomplete')
);
Enter fullscreen mode Exit fullscreen mode

Operation check (there are some unnecessary things shown...)
tags.gif

The CSS is not set, so it looks quite plain lol

Other options and CSS class names are clearly stated on github.

Impressions

It's such a convenient era.ヽ(´ー`)ノ

Top comments (0)