react-tagsinput
react-tagsinput copied to clipboard
Handling many tagsinput
How to handle many tagsinput in a form or in a same component. It seems, it isn't supported
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:
- Have state.tags as an Object whereby each key refers to each input and each value is a list.
- The
handleChangefunction on the form now needs to take a reference to the input as well as the tags, and update thestate.tagsObject with that key/value. - Each TaggedInput needs to parse the
state.tagsObject 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.