0

I am new to React native. I have a noob question related to moving code away from the main function which is render() and put the code into a different function.

Let's say I have the following code:-

render() {
 return (
   <View>

   <Modal
     animationType={"fade"}
     transparent={true}
     visible={this.state.signUpPopUpVisible}
     onRequestClose={() => {alert("Modal has been closed.")}}>
      {/* Other modal codes */}
   </Modal>

  <View style={styles.mainView}>
      {/* Other mainView codes */}
  </View>

  </View>
);

}

How can I move the whole code

   <Modal
     animationType={"fade"}
     transparent={true}
     visible={this.state.signUpPopUpVisible}
     onRequestClose={() => {alert("Modal has been closed.")}}>
      {/* Other modal codes */}
   </Modal>

into a different function and call it in the render()?

Thanks.

2 Answers 2

2

you can try doing it this way,

showModal = () => {
    return (<Modal
      animationType={"fade"}
      transparent={true}
      visible={this.state.signUpPopUpVisible}
      onRequestClose={() => { alert("Modal has been closed.") } }>
      {/* Other modal codes */}
    </Modal>);
  }
  render() {
    return (
      <View>
        {this.showModal()}
        <View style={styles.mainView}>
          {/* Other mainView codes */}
        </View>
      </View>
    );
  }
Sign up to request clarification or add additional context in comments.

1 Comment

this.showModal is not a function call. It's just the function prototype.
2

All you need is to return your object within another function the same as you did in render.

Example:

yourFunction(){
  return(
    <View></View>
  );
}

Sample of your code:

render() {
 return (
   <View>
      {this._renderModal()}
      <View style={styles.mainView}>
          {this._renderMainViewCode()}/* Other mainView codes */
      </View>
  </View>
 );
}

_renderModal(){
  return(
    <Modal
      animationType={"fade"}
      transparent={true}
      visible={this.state.signUpPopUpVisible}
      onRequestClose={() => {alert("Modal has been closed.")}}>
       {this._renderModalCode()}/* Other modal codes */
    </Modal>
  );
}

_renderModalCode(){
  return(
    <Text>This is the modals code</Text>
  );
}

_renderMainViewCode(){
  return(
    <Text>This is the main views code</Text>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.