ton1
ton1

Reputation: 7628

How to apply blur effect to background when modal is opened in React?

I think the title is not easy to understand, What I mean is when we use UI library like Bootstrap, Material UI, etc... When we click the button to show modal, the background opacity except its modal is changed to dark.

https://material-ui.com/components/modal/#modal

You can see in above url when you click the button to show modal. The background changed like blur effect.

I don't use above library, I just want to make it myself. Below is my code, Can you give me some hints? I think I might to apply style to document, Is there any good idea?

https://codesandbox.io/s/frosty-newton-icl0e

Upvotes: 5

Views: 17236

Answers (2)

Anglesvar
Anglesvar

Reputation: 1154

This can be done with CSS. Change the opacity level on other elements. Properties you may require would be filter and opacity Try Ant Design as you're using React JS. This has components prebuild with properties like visible to make background darker when some element is active.

Upvotes: 0

Mosh Feu
Mosh Feu

Reputation: 29239

You just need to wrap the <Modal /> with another div which will be the "overlay" and will has the dark background

const ModalContainer = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5)
`;
<ModalContainer>
  <Modal>I am a modal, I want to be special.</Modal>
</ModalContainer>

Working example: https://codesandbox.io/s/friendly-lake-ic9jx

If you want to place the modal exactly in the center, you can use flexbox

const ModalContainer = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
`;

const Modal = styled.div`
  background: #fff;
  border: 1px solid #000;
  padding: 20px;
  min-height: 200px;
`;

Upvotes: 4

Related Questions