Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: onPress on component doesn't function

So I am using react-native-router-flux for my navigation in my ReactJS app but I am having difficulties using it with components.

For example the following code snippet works perfectly by pushing the next page when clicking the links.

export default class MainMenuPage extends Component {
  render() {
    return (
      <View>
        <Text>Main Menu</Text>
        <TouchableOpacity onPress={Actions.bookmarksPage}>
          <Text>Bookmarks</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={Actions.settingsPage}>
          <Text>Settings</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

While the following code snippet nothing happens when you press the links.

export default class MainMenuPage extends Component {
  render() {
    return (
      <View>
        <Text>Main Menu</Text>
        <MenuButton name="Bookmarks" onPress={Actions.bookmarksPage} />
        <MenuButton name="Settings" onPress={Actions.settingsPage} />
      </View>
    );
  }
}

class MenuButton extends Component {
  render() {
    return(
      <TouchableOpacity>
        <Text>{this.props.name}</Text>
      </TouchableOpacity>
    );
  }
}

Obviously the second code snippet is much more cleaner.

like image 287
Joseph An Avatar asked Jul 13 '16 21:07

Joseph An


1 Answers

You have to pass the onPress prop through to the TouchableOpacity:

class MenuButton extends Component {
  render() {
    return(
      <TouchableOpacity onPress={this.props.onPress}>
        <Text>{this.props.name}</Text>
      </TouchableOpacity>
    );
  }
}
like image 182
TimoStaudinger Avatar answered Nov 03 '22 07:11

TimoStaudinger