Search code examples
react-nativereact-native-paper

How to disable one button when another button is pressed in react-native-paper


In react-native-paper (or even in react-native dirctly) I don't understand how to do the equivalent of getElementById to modify an element. In JavaScript, I would assign each button a unique id, and then when one button is clicked, I can call function that will disable/enable the other button based on its id.

However I am not seeing how to accomplish this task in react-native-paper (or react-native either).

Here is sample code:

import React from 'react';
import {View, Alert} from 'react-native';
import {Button} from 'react-native-paper';

export default class App extends React.Component {
  render() {
    return (
    <View>
      <Button mode="contained" color="green" onPress={() => this.buttonOnePressed()}>Button One</Button>
      <Button mode="contained" color="red" onPress={() => this.buttonTwoPressed()}>Button Two</Button>
    </View>
    );
  }

  buttonOnePressed() {
    // If Button Two is disabled, then enable it.
    // If Button Two is enabled, then disable it.
    Alert.alert('Button ONE pressed');
  }

  buttonTwoPressed() {
    // Do something when Button Two is pressed
    Alert.alert('Button TWO pressed');
  }

}

Solution

  • In your code make a state for the 1st button and another state for the 2nd button. Then by handling the state of the 2, you can achieve what you want

    Here's a sample code:

    export class default Test extends React.Component{
        constructor(props){
            super(props);
            this.state = {
                firstButtonEnable: false,
                secondButtonDisable: false,
            }
            this.handlingButton = this.handlingButton.bind(this)
        }
    
        handlingButton(){
            firstButtonEnable
            ?  this.setState({secondButtonDisable: true})
            : null;
        }
        render(){
            return(
                <View>
                    <Button title='Button1' onPress={() => {
                        this.setState({firstButtonEnable: true});
                        handlingButton();
                    }} />
                    <Button disabled={secondButtonDisable} title='Button2' } />
                </View>
            )
        }
    
    }