Application 2017-10-01

Implementing a Tag Feature with Suggestions Using React Tag Autocomplete

Implement tag autocomplete feature in React using React Tag Autocomplete library with API integration.

Read in: ja
Implementing a Tag Feature with Suggestions Using React Tag Autocomplete

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');

Now we are ready.

Implementation

// Various parts omitted
<div id="react-tag-autocomplete"></div>

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"}]

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](/assets/images/posts/react-tag-autocomplete-implementation/173c6de9-b87a-6200-65ed-506e181f565e.gif)
![tags.gif](/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')
);

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.ヽ(´ー`)ノ

Tags: React
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles