Joseph An Joseph An - 4 months ago 58
Javascript Question

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.

Answer

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>
    );
  }
}