Skip to main content
2 de 2
se añadieron 24 caracteres en el cuerpo

Modal componente esto esta con TypeScript

import './modal.css';
import React, {  useRef } from 'react'
import ReactDOM from 'react-dom'
import * as CSS from 'csstype'




type ModalProps = {
  open:boolean
  children?:React.ReactNode
  bg?: CSS.Property.Color 
  onClick?: (e:React.MouseEvent<HTMLDivElement, MouseEvent>)=> void
 
}

const Modal = (props:ModalProps) =>{

    const scrollY = useRef(0)

    const bg = props.bg || 'rgba(0,0,0,0.25)' 
    const open = () =>{
        scrollY.current = window.scrollY
        const body = document.body;
        body.style.overflow = 'hidden'
        return (
            <div className='modal' style={{backgroundColor: bg}} onClick={props.onClick}>
                 {props.children}
             </div>
        )
    }
    const close = () =>{
        const body = document.body;
        body.style.overflow = ''
        if(scrollY.current > 0) window.scrollTo(0, scrollY.current);
        return null
    }


    return ( 
      props.open ?
      
      ReactDOM.createPortal(
           open()
       ,
       document.body)
      : close()

    );
    
}

export default Modal

CSS:

.modal{
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    width: 100vw;
    position: fixed;
    z-index: 2000;
    left: 0;
    top: 0;
}

Cuando de click al modal al background cambias el props open a false para cerrarlo o en el children creas un onclick para cerrar el modal tu logica.