I created a Modal using createPortal() method to render it. Then I found that modal renders twice

444 Views Asked by At

When the button inside the Post clicked, Popup will render with createPortal method outside from root element's tree.

With this code that popup renders twice.

I want to render it only once.

Here's the parent Post component.

import { useState } from 'react';
import PopupModal from './PopupModal/PopupModal';
import './Post.css';
    const Post = (props) => {
        const postData = props;
    
        const [isOpen, setIsOpen] = useState(false);
        return (
            <div className="post-container">
                <div className="post-img-container">
                    <img className="post-img" src={props.img} alt="Travels" />
                </div>
                <div className="post-text-container">
                    <h4 className="post-heading">{props.title}</h4>
                    <p className="post-para">{props.description}</p>
                    <h1 className="post-price">{props.price}</h1>
                    <div className="post-btn-container">
                        <button onClick={() => setIsOpen(true)} className="post-btn">
                            Check Availability
                        </button>
                        <PopupModal dataData={postData} open={isOpen} onClose={() => setIsOpen(false)}>
                            Button123
                        </PopupModal>
                    </div>
                </div>
            </div>
        );
    };
    
    
    export default Post;
And here's the popupModal
import React from 'react';
import ReactDOM from 'react-dom';
import '../PopupModal/popupModal.css'

const MODAL_STYLES = {
    position: 'fixed',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%,-50%)',
    background: '#fff',
    width: '40vw',
    height: '90vh',
    padding: '50px',
    zIndex: 1000,
};

const PopupModal = ({ open, children, onClose ,dataData }) => {
    if (!open) return null;

    console.log('xxx');
    console.log(dataData);

    return ReactDOM.createPortal(
        <>
            <div className='modal-overlay' ></div>
            <div className='modal-container'>
                <button onClick={onClose}> Popup Close</button>
                {children}
            </div>
        </>,
        document.getElementById('portal')
    );
};

export default PopupModal;

Here's how I figured it rendered twice.

enter image description here

Here's the Popup with overlay around it which covers the background. enter image description here

Thanks in advance!

1

There are 1 best solutions below

0
On

Try following

{
     isOpen && <PopupModal dataData={postData} open={isOpen} onClose={() => setIsOpen(false)}>
                   Button123
               </PopupModal> 
}