rafaelmotta / react-native-tag-select

🏷 A simple tag component to act as radio button / checkbox
156 stars 43 forks source link

How can I make only one tag selected? #15

Open kimho opened 5 years ago

kimho commented 5 years ago

How can I make only one tag selected like radio button?

liukefu2050 commented 5 years ago

Copy classes and add this code to TagSelect.js

componentDidUpdate (prevProps, prevState, prevContext) {

if (prevProps !== this.props) {

  const value = {}

  this.props.value.forEach((val) => {

    value[val[[this.props.keyAttr]] || val] = val

  })

  this.setState({ value })

}

}

example: <TagSelect value={[this.state.currItem]} theme="default" max={1} ref={(tag) => { this.tag = tag; }} onItemPress={(item) => { this.setState({currItem:item}) }} data={data} />

raheelshan commented 4 years ago

You can extend class like this.

` import { TagSelect } from 'react-native-tag-select';

class TagSelectExtension extends TagSelect {

    handleSelectItem = (item) => {
        const key = item[this.props.keyAttr] || item

        const value = []
        const found = this.state.value[key]

        value[key] = item
        return this.setState({ value }, () => {
            if (this.props.onItemPress) {
                this.props.onItemPress(item)
            }
        })
    }

}

export default TagSelectExtension

`

Now instead of using TagSelect.js import TagSelectExtension.js and use it. this is safe way. Also notice when extending React.Component extend TagSelect.