UnluckyLAD
UnluckyLAD

Reputation: 189

Single selection item that saves the state (REACT-NATIVE)

I currently have 4 TouchableHighlights and my code looks as follows:

state:

      this.state = {
                    selected: null,
                    selectedButton: ''
                   }

Touchable Highlight (they're all the same except for text)

 <TouchableHighlight
                    onPress={this.selectedButton}
                    underlayColor='blue
                    style={[styles.box, { backgroundColor: (this.state.selected === true ? 'red' : 'blue') }]}>
                    <Text>1</Text>
                </TouchableHighlight>

my functions:

  selectedButton = () => {
        this._handlePress('flag', '1')
        this.setState({
            selected: true,
        });
    };

_handlePress(flag, button) {
    if (flag == 1) {
        this.setState({ selected: true });
    }
    this.setState({ SelectedButton: button })
}

Current behaviour: Whenever I select one button, all become highlighted and cannot be unpressed. Desired behaviour: I want only one button to be selected at the time with its state being saved somewhere.

Note: I could get the desired behaviour by creating 4 different functions that contain a different flag number, however, I'd like to get this done in the cleanest way possible.

Any guidance please?

Thank you

Upvotes: 0

Views: 44

Answers (1)

RavenMan
RavenMan

Reputation: 1933

You can create an array of button texts, then use .map(), which provides the current index value, to iterate through them. For example:

render() {
    const renderHighlight = (text, index) => (
        <TouchableHighlight 
            onPress={() => {
                if(this.state.selectedIndex === index) {
                    // "Unpress" functionality
                    this.setState({selectedIndex: undefined});
                } 
                else {
                    this.setState({selectedIndex: index
                }
            })
            style={this.state.selectedIndex === index ? 
                {backgroundColor: "#0F0" : {}}
        >
            <Text>{text}</Text>
        </TouchableHighlight>;
    );

    const buttons = ["button 0", "button 1", "button 2"];

    return buttons.map((text, i) => this.renderHighlight(text, i));
}

Upvotes: 2

Related Questions