Display custom modals in React that showcase content for a brief moment before the page refreshes

I recently developed a custom modal in React. When the Open button is clicked, showModal is set to true and the modal display changes to block. Conversely, clicking the Close button sets the display to none.

However, I noticed a bug where upon refreshing the page, the content of the modal briefly appears on screen for a few milliseconds.

This functionality is crucial for my application.

If you want to see it in action, check out this video link: https://youtu.be/A6CUmSzwobY

You can also view the code on CodePen by following this link:

https://codepen.io/alligatorio/pen/aYzMKL?editors=0100

Any help in identifying and resolving this issue would be greatly appreciated.

Answer №1

If you want to ensure that the modal is only added to the DomTree when it's supposed to be open, one approach is to use return null when the modal is closed.

const Modal = ({ handleClose, show, children }) => {

  // Check if the modal is closed and return null
  if (!show) {
    return null;
  }

  // If the modal is open, render its content
  return (
    <div className={'modal display-block'}>
      <section className='modal-main'>
        {children}
        <button
          onClick={handleClose}
        >
          Close
        </button>
      </section>
    </div>
  );
};

Check out the code on Codepen: https://codepen.io/anon/pen/drojdr?editors=0111

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

«Modify Apollo Client settings to accommodate JWT authentication»

Is there a way to set up a token in my apollo client when the user logs in? I've been struggling with this issue. This is what I currently have in my index.js: const client = new ApolloClient({ ssrMode: SERVER_MODE, cache: new InMemo ...

Unscramble the pairs in this React JS two-column puzzle!

I am working on a project that requires me to create pairs of matches/links from two vertical lists. An example pair list could look like this: const [pairs, setPairs] = useState([ { id: 1, left: "Apple", right: "Red" }, { id: ...

If the URL matches a specific path, then append a parameter

I've created a script that adds a parameter to a URL based on specific subfolders. For example, if the URL contains /de, it will add ?_sft_language=german. However, I'm encountering an issue where the code is running multiple times instead of jus ...

Angular HTML layout designed for seamless interaction

<div class ="row"> <div class ="col-md-6"> Xyz </div> <div class ="col-md-6"> Abc </div> </div> Using the code above, I can easily create a layout with two columns. Th ...

Encountered an issue loading resource: net::ERR_BLOCKED_BY_CLIENT while attempting to access NuxtJS API

After deploying my NuxtJS 2 app on Vercel and adding serverMiddleware to include an api folder in the nuxt.config.js file, everything was working smoothly. However, when I tried making an api call on my preview environment, I encountered an error: POST htt ...

Unable to access Firebase Key/Value pairs

I've set up the following data structure in my Firebase database. { "data": { "lava14mod1":"down", "lava14mod2":"up" } } In my React app, I have access to this data but can only retrieve it as a combined (key,value) pair within a singl ...

Java script pop-up notifications always show up

This Text Goes Above the Form <?php require_once "core-admin/init-admin.php"; if( !isset($_SESSION['admin_username']) ){ $_SESSION['msg'] = 'page cannot be opened'; header('Location:admin_login.php&ap ...

The styling in CSS does not accurately reflect its relationship to the parent

My code includes a div with the ID of "outer" nested inside a parent div with the ID of "Container". I'm attempting to adjust the properties of the outer div relative to its parent, meaning its width, height, and other attributes should be based on th ...

Is it possible to find a more efficient approach than calling setState just once within useEffect?

In my react application, I find myself using this particular pattern frequently: export default function Profile() { const [username, setUsername] = React.useState<string | null>(null); React.useEffect(()=>{ fetch(`/api/userprofil ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

From jQuery to HTML to PHP, then back to HTML from PHP through jQuery

Hey, I have a code snippet that I'm working on: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script type="text/javascript"> function get() { $.post(' ...

Upcoming construction: Issue encountered - The Babel loader in Next.js is unable to process .mjs or .cjs configuration files

Within my package.json file, I have set "type": "module" and "next": "^12.2.5". In my tsconfig.json: { "compilerOptions": { "target": "ES2022", "module": "esnext ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Elevate the appearance of your UI with stylish Material text

I'm struggling to customize a material-ui textfield to achieve my desired look. I simply want a clean and plain white input field with the standard MUI animations. It's important that the textfield always has a white background and the text appea ...

When the screen is at mobile width, elements with the class "Responsive" are hidden using the display:none; property. These elements can be

Hey there! So, I've got this cool interactive banner on my website. It features 2 slider sections with some awesome products on the right side. The layout is responsive, meaning that when you switch to a mobile screen size (around 515px or less), the ...

Unable to apply Login Form Css to HTML

Creating a Login Form <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Login Form</title> <link rel = "stylesheet" type="text/css" href="{{ ...

What exactly does Apple consider as a "user action"?

In the midst of my current web project, I am facing a challenge with initiating video playback after a swipe event. Despite utilizing the HTML5 video player and JavaScript to detect swipes, I have encountered difficulties in achieving this functionality. I ...

Unable to eliminate top margin in Bootstrap 3 affix feature

Struggling to locate the source of the margin-top when utilizing the affix plugin on my Navbar. You can view [my website here] for better understanding. Should I be implementing Javascript to solve this issue? My current skills in that area are not very ...

Filtering a subarray in Angular using ng-repeat

While working with Angular, I am attempting to filter data using ng-repeat based on the FactorName property in the given schema. Unfortunately, trying to use <... ng-model="query.Factors.FactorName" ...> as a filter does not produce the desired re ...

Tips for utilizing the randomColor library

Looking for guidance on incorporating the randomColor package from yarn to assign colors to various columns in a table within my project. Any examples or resources would be greatly appreciated! I am specifically working with React and Typescript. ...