Kabu
Kabu

Reputation: 579

Integrate redux form with react tag autocomplete

Anyone able to get React Tag Autocomplete work with redux form and have redux form do the management of data? https://github.com/i-like-robots/react-tags

Upvotes: 0

Views: 338

Answers (1)

Piyush Dhamecha
Piyush Dhamecha

Reputation: 1515

Basically, in redux-form you can create a custom component and use it into form

In your case, you have to create a custom component for react-tags like this

import React from "react";
import ReactTags from "react-tag-autocomplete";

const TagAutocomplete = ({ input: { value, onChange } }) => {
  const suggestions = [
    { id: 1, name: "Apples" },
    { id: 2, name: "Pears" },
    { id: 3, name: "Bananas" },
    { id: 4, name: "Mangos" },
    { id: 5, name: "Lemons" },
    { id: 6, name: "Apricots" }
  ];

  console.log(value);

  const newValue = !value
    ? []
    : value.map(id =>
        suggestions.find(({ id: sugestionId }) => id === sugestionId)
      );

  const handleDelete = i => {
    const tags = [...value];
    tags.splice(i, 1);
    onChange(tags);
  };

  const handleAdd = e => {
    onChange([...value, e.id]);
  };

  return (
    <ReactTags
      tags={newValue}
      suggestions={suggestions}
      handleDelete={handleDelete}
      handleAddition={handleAdd}
    />
  );
};

export default TagAutocomplete;

And import into redux form

import React from "react";
import { Field, reduxForm } from "redux-form";

import TagAutocomplete from "./TagAutocomplete";

const SimpleForm = props => {
  const { handleSubmit, pristine, reset, submitting } = props;
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Auto complete</label>
        <div>
          <Field name="autoComplete" component={TagAutocomplete} />
        </div>
      </div>
      <div>
        <button type="submit" disabled={pristine || submitting}>
          Submit
        </button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>
          Clear Values
        </button>
      </div>
    </form>
  );
};

export default reduxForm({
  form: "simple" // a unique identifier for this form
})(SimpleForm);

Check this codesanbox for live demo https://codesandbox.io/s/redux-form-simple-example-mg47k

Upvotes: 1

Related Questions