Nick
Nick

Reputation: 865

How to use onPress on a custom component?

Let's assume I have this custom component:

export default class Button extends Component {
  render(){
    return(
      <TouchOpacity>
        <Text> Button </Text>
      </TouchOpacity>
    )
  }
}

And I use it in a parent component like this :

export default class MainPage extends Component {
  render(){
    return(
      <Button onPress={ this.doSomething }></Button>
    )
  }
}

For some reason (unknown to me at least) this onPress even won't happen. I'm pretty new to react-native btw. I believe I must find a way to enable this kind of event handling.

Is it possible to get a small example how to achieve that based on my examples above ?

Upvotes: 22

Views: 21112

Answers (2)

Nick
Nick

Reputation: 865

So, just found out how to handle this.

export default class Button extends Component {
  constructor(props){
    super(props)
  }
  render(){
    return(
      <TouchableOpacity
      onPress={this.props.onPress}
      >
        <Text> Button </Text>
      </TouchableOpacity>
    )
  }
}

and

export default class MainPage extends Component {
  render(){
    return(
      <Button onPress={ this.doSomething }></Button>
    )
  }
}

Long story short: since the onPress I'm passing is a prop in the MainPage, I'm passing it a function (this.doSomething) which later on is activated in Button's onPress.

Upvotes: 41

Rajesh N
Rajesh N

Reputation: 6673

Nick's answer is right.Along with that if you want to call separate function for both child and parent component then you can use onPressOut. This will help to manage state of componant

export default class Button extends Component {
  constructor(props){
    super(props)
  }

onClickListen = () => {
        if (this.state.isSelected === false) {
            this.setState({isSelected:true});
            isSelectedPass=true;
        }
        else {
            this.setState({isSelected:false});
            isSelectedPass=false;

        }
    }

  render(){
    return(
      <TouchableOpacity
      onPress={this.props.onPress} onPressOut={this.onClickListen}
      >
        <Text> Button </Text>
      </TouchableOpacity>
    )
  }
}

export default class MainPage extends Component {
  render(){
    return(
      <Button onPress={ ()=>this.doSomething }></Button>
    )
  }
}

Upvotes: 1

Related Questions