Skip to content

Instantly share code, notes, and snippets.

@amiralies
Created January 8, 2019 16:40
Show Gist options
  • Select an option

  • Save amiralies/c25bd2b860a0bc5d22493c0eba48a0f2 to your computer and use it in GitHub Desktop.

Select an option

Save amiralies/c25bd2b860a0bc5d22493c0eba48a0f2 to your computer and use it in GitHub Desktop.

Revisions

  1. amiralies created this gist Jan 8, 2019.
    78 changes: 78 additions & 0 deletions SelectList.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    class SelectableItem extends React.Component {
    constructor() {
    super();

    this.handleOnPress = this.handleOnPress.bind(this);
    }

    shouldComponentUpdate(nextProps) {
    const { isSelected } = this.props;
    return isSelected !== nextProps.isSelected;
    }

    handleOnPress() {
    const { onPress } = this.props;
    onPress();
    }

    render() {
    const { isSelected, text } = this.props;
    const textColor = isSelected ? 'blue' : 'black';

    return (
    <TouchableOpacity onPress={this.handleOnPress}>
    <View>
    <Text style={{ color: textColor }}>{text}</Text>
    </View>
    </TouchableOpacity>
    );
    }
    }

    class SelectList extends React.Component {
    constructor() {
    super();

    this.handleOnPressItem = this.handleOnPressItem.bind(this);
    this.state = {
    selected: new Map(),
    };
    }


    onPressItem(id) {
    this.setState((state) => {
    const selected = new Map(state.selected);
    selected.set(id, !selected.get(id));
    return { selected };
    });
    }


    renderItem({ item }) {
    const { selected } = this.state;

    return (
    <SelectableItem
    id={item.id}
    onPressItem={this.handleOnPressItem}
    selected={!!selected.get(item.id)}
    title={item.title}
    />
    );
    }


    render() {
    const { data } = this.props;

    return (
    <FlatList
    data={data}
    extraData={this.state}
    keyExtractor={item => item.id}
    renderItem={this.renderItem}
    />
    );
    }
    }