domshyra
domshyra

Reputation: 952

Issue showing modal with react hooks on bootstrap 5

I am getting a console error when I am using this component.

ParseExceptionsModal.jsx:18 Uncaught TypeError: Cannot read property 'show' of null

Here is ParseExceptionsModal.jsx

import { Modal } from 'bootstrap';
import React, { useState, useEffect, useRef } from 'react';
import ParseExceptions from './ParseExceptions';

const ParseExceptionsModal = (props) => {
   const [modal, setModal] = useState(null);
   const parseExceptionModal = useRef();


   useEffect(() => {
       setModal(new Modal(parseExceptionModal.current), {
          keyboard: false,
    });
       if (props.json.length > 0) {
          modal.show(); //Here is the culprit. but why is it null?
       }
    }, []);

   return (
    <>
        <div
            className="modal fade"
            tabIndex="-1"
            role="dialog"
            ref={parseExceptionModal}
            aria-labelledby="parseExceptionModal"
            aria-hidden="true">
            <div className="modal-dialog" role="document">
                <div className="modal-content">
                    <div className="modal-header">
                        <h5 className="modal-title">{props.title}</h5>
                        <button type="button" className="btn-close" onClick={() => modal.hide()} aria-label="Close">
                            {/*<span aria-hidden="true">&times;</span>*/}
                        </button>
                    </div>
                    <div className="modal-body">
                        <ParseExceptions json={props.json} />
                    </div>
                    <div className="modal-footer">
                        <button onClick={() => modal.hide()} type="button" className="btn btn-outline-secondary">
                            Dismiss
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </>
   );
};
export default ParseExceptionsModal;

My assumption is that setModal would init modal for me and not be null. I have seen it done like this but I only need to show this modal if my json contains elements. Which is why I figured after setting modal I can show it if there props.json.length > 0.

Here is how to render a modal in js with bootsrtrap 5

Any issues in the react code? Or is something happening async and I need to wait for bootsrap to set the modal? Not sure what is happening here.

Thanks

Upvotes: 2

Views: 1646

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362350

Don't instantiate it while setting the state. Instead use a variable...

   useEffect(() => {
        const modal = new Modal(parseExceptionModal.current, {keyboard: false})
        setModal(modal)
        modal.show()
   },[])

Codeply

Upvotes: 2

Related Questions