Marc
Marc

Reputation: 129

How to know which button has been pressed? React

I have two buttons like this:

<TouchableOpacity onPress={() => this.setModalVisible(true)} style={stylesDropDown.acceptButton}>
                        <Text> Accept </Text>
</TouchableOpacity>
<TouchableOpacity  onPress={() => this.setModalVisible(true)} style=stylesDropDown.refuseButton}>
                        <Text> Refuse </Text>
</TouchableOpacity>

I want that when the 'setModalVisible' function is executed to know which of these two buttons has been pressed. Any ideas?

Upvotes: 0

Views: 620

Answers (4)

Phaoga55
Phaoga55

Reputation: 71

just make it in 2 function

pressBtn1 =()=>{ 
     setModalVisible(true)
}
pressBtn2 =()=>{ 
     setModalVisible(true)
}

and in the dom:

<TouchableOpacity onPress={pressBtn1} style={stylesDropDown.acceptButton}>
                        <Text> Accept </Text>
</TouchableOpacity>
<TouchableOpacity  onPress={pressBtn2} style=stylesDropDown.refuseButton}>
                        <Text> Refuse </Text>
</TouchableOpacity>

Upvotes: 0

llandino
llandino

Reputation: 75

You could try something like:

    const handleBtn = (e) =>{
     setModalVisible(true)
     console.log(e.target.id)

    }

and in the DOM:

<TouchableOpacity id="btn_1" onPress={handleBtn} style=stylesDropDown.refuseButton}>
      <Text> Rechazar </Text>
</TouchableOpacity>

Upvotes: 1

Ketan Ramteke
Ketan Ramteke

Reputation: 10655

You an console.log the button which is pressed,

here is how:

    <TouchableOpacity
      onPress={() => {
        setModalVisible(true);
        console.log('Aceptar Clicked');
      }}
      style={stylesDropDown.acceptButton}>
      <Text> Aceptar </Text>
    </TouchableOpacity>
    <TouchableOpacity
      onPress={() => {
        setModalVisible(true);
        console.log('Rechazar Clicked');
      }}
      style={stylesDropDown.refuseButton}>
      <Text> Rechazar </Text>
    </TouchableOpacity>

Upvotes: 0

KingPineapple
KingPineapple

Reputation: 56

I can't comment because of low score but try:

onPress={event => {
    const whoAmI = event.target; //Change to what you want to get from clicked element
    this.setModalVisible(true)
}}

Upvotes: 0

Related Questions