简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM