react-tagsinput icon indicating copy to clipboard operation
react-tagsinput copied to clipboard

Handling many tagsinput

Open kabrice opened this issue 7 years ago • 1 comments

How to handle many tagsinput in a form or in a same component. It seems, it isn't supported

kabrice avatar May 05 '18 18:05 kabrice

Each individual input needs to have an Array as its value. In the single input example that's state.tags. To handle multiple inputs I've had to do a couple of things:

  1. Have state.tags as an Object whereby each key refers to each input and each value is a list.
  2. The handleChange function on the form now needs to take a reference to the input as well as the tags, and update the state.tags Object with that key/value.
  3. Each TaggedInput needs to parse the state.tags Object to get the relevant tags as an Array out of the Object stored in state.

Here's the important parts of what I've done:

class Form extends React.Component {
     constructor(props) {
        this.handleChange = this.handleChange.bind(this);
        this.state = {
            tags: {}  // Store an object instead of `[]`
        }
    }

    handleChange(inputId, tags) {
        // Update state.tags to look like:
        // {input1: [1, 2, 3], input2: [4, 5, 6]}
        let tagStateUpdateObject = {};
        tagStateUpdateObject[inputId] = tags;

        const newTagsState = Object.assign({}, this.state.tags, tagStateUpdateObject );

        this.setState({
            ...this.state,
            'tags': newTagsState
        });
    }

   // and then render multiple inputs...
   // While passing some props:
   //   1. `handleChange` function 
   //   2. A unique `inputId` value
   //   3. The contents of `this.state.tags`

}
class FormInput extends React.Component {
    constructor(props) {
        super(props);
        this.handleTagChange = this.handleTagChange.bind(this);
    }

    handleTagChange(tags) {
        // This just sends the tags which you've input to the form's handleChange function
        // but it must also send the inputId for this specific input.
        this.props.handleChange(this.props.inputId, tags);
    }

    render() {
        const inputvalue = this.props.tags[imageId] || [];
        return <TagsInput value={inputValue} onChange={this.handleTagChange} />
    }
}

Hope this helps someone out there.

tomharvey avatar Jul 24 '19 10:07 tomharvey