My react-native app is having trouble with modal closure

As I develop an app, I encounter an issue with Modal usage across different screens. I have created a universal component for handling all Modals. By passing JSX and toggling visibility based on a Global variable, the problem arises when switching screens. The Modal from the previous screen remains visible in the background.

Although I attempted to control visibility using both a Global variable and a local one, the Modal still fails to close properly.

Here is the common Modal component I am using:

  render() {
    let { GlobalStore, renderContent = () => {}, modalStyle, modalHeight = '50%' } = this.props;
    return (
      <Modal
        isVisible={GlobalStore.showModal}
        backdropColor={Constants.COLORS.BLACK}
        backdropOpacity={0.4}
        onBackdropPress={() => GlobalStore.toggleModal(false)}
        style={[styles.bottomModal,modalStyle]}>
        <View style={[styles.modalContent,{height: modalHeight}]}>
          {renderContent}
        </View>
      </Modal>
    )
  }
}

and implementation on screens:

   {this.openModal?
    <CustomModal visible={GlobalStore.showModal&&this.openModal} 
      modalHeight = {this.modalHeight} renderContent = 
      {this.ModalContent()}/>
       :
     null
    }

My goal is to close previous modals that appear in the background without creating separate files for each Modal. Any assistance would be greatly appreciated. Thank you.

Answer №1

Modify GlobalStore.showModal to be a string instead of a boolean value.

    //update action function
    const showModal = (modalType = "GLOBAL") => ({type: "SHOW_MODAL", modalType})


    //common modal usage
    //trigger action
    dispatch(showModal());
    //check for visibility using the global string
    <Modal
        isVisible={GlobalStore.showModal === "GLOBAL"}
        {...restProps}
    />


    //custom modal usage
    //trigger action with custom string
    dispatch(showModal("CUSTOM_MODAL"));
    //check for visibility using the custom string
    <CustomModal
        isVisible={GlobalStore.showModal === "CUSTOM_MODAL"}
        {...restProps}
    />

    //hide all modals
    dispatch(showModal(""))

Answer №2

While models are indeed special components that overlay content, it's important for them to be properly managed by their parent components. If previous screens are not being unmounted and a single global variable is being used, it can lead to all unmounted modals retaining a true value. One solution could be moving the visibility variable to the component's state and limiting its scope, or alternatively, naming and distinguishing various modals to ensure the global variable only refers to one modal at a time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the features of mobile search criteria filtration in jQuery

I have a homepage with various criteria that users can select such as budget maximum and minimum. When they click on the "search" button, I want it to lead them to a list of links on another page that corresponds to their search using jQuery Mobile and ...

Angularjs scope throws TypeError when attempting to add an array

As someone diving into the world of Angular and JavaScript, I am tackling the challenge of creating a directive that requires adding an array to the directive's scope. Here's a snippet of the code for my directive: .directive("startupSections", ...

Journey Swiftly Control

I have a question. Is it possible to manipulate routes in Express? Can I assign multiple routes to the same get or post request when providing an address? module.exports = function (app) { var controller = app.controllers.maps.cliente; app.route(&apos ...

Can we address certain data before the $stateChangeStart event is triggered?

I have been working on creating a custom Role-Permissions system that I want to set up during the initial root state resolve: $stateProvider .state('common', { resolve:{ user: function(AclService, UserService) { UserService. ...

What is the best way to retrieve dates from a MySQL database using ExpressJS?

My current task involves retrieving the date value from a MySQL server, but upon printing the result, I encounter an error. In my code, I am able to fetch the date value, however, when attempting to print it, there seems to be an issue with the output. (F ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...

Transferring session data through AJAX in PHP

I'm currently developing an app using PhoneGap. However, PhoneGap only supports HTML, CSS, and JS, not PHP. This led me to the workaround of placing the PHP file on a remote server and using AJAX to call it via the server's URL. My issue now is ...

Ensuring Stringency in JQuery's '$' Selector

I have a specific data attribute within the div element that is displayed in the HTML. <div my-custom-attrib="1".../> <div my-custom-sttrib="2"...> Now, in JQuery, I am attempting to filter between the div elements based on the value of the c ...

JavaScript form callbacks in Rails 3 are failing to trigger

My Rails 3 callbacks are not triggering for some unknown reason. Here's the form code I'm using: <%= form_tag('/create', :method => "post", :remote => true ,:id => "create") do %> <% end %> And this is the javascr ...

There was an error with CreateListFromArrayLike as it was called on a non-object

I am receiving a list of over 1000 numbers from an API and storing it in a variable called "number". My goal is to find the highest number from this list. However, I encountered an error while attempting to do so: TypeError: CreateListFromArrayLike called ...

Is there a way for us to determine the time at which the user last took a screenshot or photo?

I am currently developing a website using Django and I have a unique requirement. I need to access the last image that a user has taken on their phone, without the image being shared by anyone else. The photo must be captured by the user's device itse ...

Unable to get ng-submit function to work properly within the Laravel PHP framework

Hello everyone, I have an inquiry regarding Laravel/AngularJS. In my project, there is a form where users can post questions. However, when I click the submit button, no requests are sent (as per inspection in Google Chrome). Interestingly, the Log in int ...

Utilizing Jquery to enhance table filtering functionality

I created a table listing various places, along with buttons to filter the list. The first filter is based on location (north, east, central, south, west) determined by postcode. The other filter is for "impress" which only displays places with a rating of ...

A guide on arranging map entries based on their values

The map displayed below, as represented in the code section, needs to be sorted in ascending order based on its values. I would like to achieve an end result where the map is sorted as depicted in the last section. If you have any suggestions or methods o ...

What steps do I need to take to ensure this function runs sequentially? Perhaps my understanding of async and await is lacking

I have a function that is responsible for adding data to my database. However, I'm encountering some inconsistency where it works sometimes and fails other times. My suspicion is that the eDataBuilder function is taking too long to iterate through the ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

Is there a way to utilize the child component's method?

I am looking to access a child component's method from the parent in Vue.js. To achieve this, I plan on using $refs. Code Example: <template> <div>Parent!</div> </template> Script: <script> Vue.component('c ...

What is the best way to display all the emojis available on the server?

Recently, I've been developing a discord.js server info command. A thought crossed my mind about displaying the emojis present in a server, but I'm unsure about how to go about doing that. I've figured out how to retrieve the total number of ...