Search code examples
javascriptreactjsreact-bootstrap

React Bootstrap Modal show is not working as expected


I am trying to add react bootstrap modal in my application. In one file am dropping the Modal and trying to send the param to the modal class.

Example:

Class1 : I have this inside my render function. 

<MyModal openModal={true}/>

I am trying to send the prop from here which will open the modal.

In my Modal class, I have below code:

const MyModal = (props) => {
  const [open, showModal] = useState(props.openModal);
  const handleClose = () => showModal(false);

  return (
    <Modal show={open} onHide={handleClose} >
      //rest of the modal data 
    </Modal>
  );
};

export default MyModal;

My prop is always showing the updated value coming from class 1. But Modal class is not getting rendered as per the update props. After closing the modal for 1st time, it remain close until I refresh my screen.

My using https://react-bootstrap.github.io/components/modal/ modal link for refrence.

Thanks in advance for help.


Solution

  • You are missing the hook to update the component when it receive the updated props.

    You need to include useEffect() hook in your code. It will re-render the component with updated props. You MyModal class will look like below code.

    const MyModal = (props) => {
      const [open, showModal] = useState(props.openModal);
    
      useEffect(() => {
        showModal(props.openModal);
      }, [props]);
    
      const handleClose = () => showModal(false);
    
      return (
        <Modal show={open} onHide={handleClose} >
          //rest of the modal data 
        </Modal>
      );
    };
    
    export default MyModal;