Blurring background when React portal is displayed

14,529

Solution 1

Every child of the element that you blur will have that filter applied. Since you have similar code to the portal docs then im going to assume your html structure is something like this

<html>
  <body>
    <div id="app-root"></div>
    <div id="modal-root"></div>
  </body>
</html>

if this is the case then apply the filter to app-root aka...

document.getElementById('app-root').style.filter = 'blur(5px)'

Solution 2

Because your modal has fixed position, when your modal is open, to blur the background, add

  backdrop-filter: blur(8px);

or

  backdropFilter: blur(8px);

to the style of your modal body and that should do the job.

Share:
14,529

Related videos on Youtube

wildair
Author by

wildair

Updated on May 25, 2022

Comments

  • wildair
    wildair about 2 years

    I'm using React portals to create a modal popup after form submission. I would like to blur just the background and to show the modal like in picture 2. I used document.body.style.filter = "blur(5px) in the first picture but it blurs everything. CSS for the modal and modal root (my code is almost identical to the React docs for portals)

    ```
    #modal-root {
      position: relative;
      z-index: 999;
    }
    .modal {
      background-color: rgba(0,0,0,0.5);
      position: fixed;
      height: 100%;
      width: 100%;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: auto;
      z-index: 99999;
    }```
    

    What I have so far

    what I want it to look like

  • wildair
    wildair about 6 years
    Thank you! Of course that's the one element I didn't try to filter. Not sure if this is the best way to remove the filter on exit of the modal. document.getElementById('app-root').style.filter = 'blur(0px) grayscale(0%)' but, it works.
  • John Ruddell
    John Ruddell about 6 years
    Happy to help! :) And Yes that is a completely fine way to apply the filter, you may also be able to just set the filter to none
  • wildair
    wildair about 6 years
    I tried using 'none' in Chrome dev tools but, it didn't like it. 0px seems to work fine. Thank you again.
  • wildair
    wildair about 6 years
    I did try that. I ended up basically walking down the DOM tree in Dev tool and adding blur to every element one by one to see which element I had to target to get the desired effect. I must have missed the root element because that was the only one that worked for me.