Akashii
Akashii

Reputation: 2281

Modal not showing Reactjs using hook

I'm using react hook and react portal to create and showing up modal. Here is my code

Modal.tsx

const modalRoot = document.getElementById('modal');
const Modal: React.FC<Props> = memo(({isOpen, toggle, children}) => {
    const el = document.createElement('div');

    useEffect(() => {
        modalRoot.appendChild(el);

        return (() => {
            modalRoot.removeChild(el);
        })
    });

    return (
        isOpen ? createPortal(
            <React.Fragment>
                <div className="modal fade">
                    <div className="modal-dialog" role="document"
                         style={{width: "700px"}}>
                        {children}
                    </div>
                </div>
            </React.Fragment>, el
        ) : null
    )
});

useModal.tsx

const useModal = () => {
    const [isOpen, setIsShowing] = useState(false);

    const toggle = () => {
        setIsShowing(!isOpen);
    };

    return [
        isOpen,
        toggle,
    ]
};

Using

const [isModalOpen, toggleModal] = useModal();
    <Modal isOpen={isModalOpen} toggle={toggleModal}>
        <h1>test</h1>
        <p>Other text that describes what is happening</p>
        <button onClick={() => toggleModal(false)}>toggle</button>
    </Modal>

                        <div className="col-lg-2 pull-right">
                            <div className="pull-right">
                                <button type="button"
                                    // @ts-ignore
                                        onClick={() => toggleModal(!isModalOpen)}
                                        className="btn btn-primary btn-outline"><i
                                    className="ti-plus"/>
                                </button>
                            </div>
                        </div>

But when I click in this button. It's not showing my modal. When I press f12 and check the dom. I see modal rendered. Please help me

Upvotes: 1

Views: 587

Answers (1)

Yash Joshi
Yash Joshi

Reputation: 2774

I tried running your code on Codesandbox and it works for me properly. Here is the link: https://codesandbox.io/s/sharp-dust-oyz0c

Though I suspect you might not be seeing modal because of styling. Note the modal has fade in className. Try checking the styles or creating a codesandbox with all the necessary styles so that its easy to debug.

Hope this helps!

Upvotes: 1

Related Questions