Rohan Sethi
Rohan Sethi

Reputation: 115

React native TouchableOpacity onPress Problems

I have a simple icon button as follows :

class SideIcon extends Component {
  render() {
    return (
      <TouchableOpacity onPress={console.log('puff')} style={styles.burgerButton}>
        <Icon name="bars" style={styles.burgerIcon}/>
      </TouchableOpacity>
    );
  }
}

It's called from the following component :

export default test = React.createClass({
  getInitialState: function() {
    return {
      isModalOpen: false
    }
  },

  _openModal() {
    this.setState({
      isModalOpen: true
    });
  },

  _closeModal() {
    this.setState({
      isModalOpen: false
    });
  },
  render() {
    return (
     <View style={styles.containerHead} keyboardShouldPersistTaps={true}>
     **<SideIcon openModal={this._openModal} closeModal={this._closeModal} />**
      <Text style={styles.logoName}>DareMe</Text>
      <SideBar isVisible={this.state.isModalOpen} />
     </View>
    );
  }
});

But the onPress on the TouchableOpacity never works. Where I'm going wrong ? Although It shows console statements during the component load.

Upvotes: 7

Views: 42648

Answers (2)

Deepinder
Deepinder

Reputation: 31

Instead of passing a function, you should pass a fat arrow function to invoke your code. It should be like this

onPress={() => console.log('puff')}

Full Example is

class SideIcon extends Component {
      render() {
        return (
          <TouchableOpacity onPress={() => console.log('puff')} style={styles.burgerButton}>
            <Icon name="bars" style={styles.burgerIcon}/>
          </TouchableOpacity>
        );
      }
    }

Upvotes: 0

Tobias Lins
Tobias Lins

Reputation: 2651

You should bind a function that invokes your code.

For example:

<TouchableOpacity onPress={() => console.log('puff')} style={styles.burgerButton}>
  <Icon name="bars" style={styles.burgerIcon}/>
</TouchableOpacity>

A better way is to give it a reference to a component function

class SideIcon extends Component {
  handleOnPress = () => {
    console.log('puff')
  }
  render() {
    return (
      <TouchableOpacity onPress={this.handleOnPress} style={styles.burgerButton}>
        <Icon name="bars" style={styles.burgerIcon}/>
      </TouchableOpacity>
    );
  }
}

Upvotes: 11

Related Questions