gokujou
gokujou

Reputation: 1491

React Native: How to make a component do an action on press

I have a large component/view that fills most the screen. I want it to show some additional information on press. Is there a way to have the main component catch the press event, or does it need to be caught by a child component inside that fills the main one (trying to avoid using an extra child to keep everything more clean)?

I would like to have something like this, even better if the onPress could be set internally:

Main View:

<MainComponent onPress={ /* Call the components onPress */ } />

Main Component:

export default class MainComponent extends Component {
  ...

  onPress() {
    // display additional data
  }
}

Thank you.

Upvotes: 0

Views: 4317

Answers (2)

Adrien Lacroix
Adrien Lacroix

Reputation: 3612

On React-Native, handling touches is done with Touchables components. (official doc)

You can use any of these native components depending on your use. For example, if you just want to catch the press event on your main component, you can wrap it under a TouchableWithoutFeedback (doc), and use the onPress prop.

export default class MainComponent extends Component {
  ...

  onPress() {
    // display additional data
  }

  ...

  render() {
    return (
        <TouchableWithoutFeedback onPress={() => this.onPress()}>
            <View>
               ...
            </View>
        </TouchableWithoutFeedback>
    )
  }
}

Upvotes: 4

Wojtek
Wojtek

Reputation: 439

You can wrap your component in one of the components that is able to handle touches.

export default class MyComponent extends Component {

  render() {    
    return (
      <TouchableWithoutFeedback onPress={this.props.onPress}>
        <View>
          <Text>My Component</Text>
        </View>
      </TouchableWithoutFeedback>
    );
  }
}

Then in Main View:

<MyComponent onPress={ () => console.log("Pressed!") } />

You can read more about handling touches in official RN docs: https://facebook.github.io/react-native/docs/handling-touches.html

Upvotes: 2

Related Questions