Xameer
Xameer

Reputation: 31237

Bootstrap modal not working in React typescript app but working on the fiddle

As per my current research:

Here is a debug version https://preprod-ansaar.web.app/

I have implemented a bootstrap modal in my app.tsx:

import React from 'react';
const app: React.FC = () => {
  return (
    <div>
      <button id="btn1">Show Modal</button>
      <br />
      <button data-onclick="alert('Button Clicked')">Another Button</button>


      <div className="modal fade" id="myModal" data-tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="myModalLabel">Modal Title</h4>
            </div>
            <div className="modal-body">
              Modal Body
      </div>
            <div className="modal-footer">
              <button className="btn btn-default" data-dismiss="modal">Close</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default app;

My index.css is:

#myModal {
  position: relative;
}

.modal-dialog {
  position: fixed;
  width: 100%;
  margin: 0;
  padding: 10px;
}

And in the index.html I have:

  <script>
    $('#btn1').click(function () {
      // reset modal if it isn't visible
      if (!($('.modal.in').length)) {
        $('.modal-dialog').css({
          top: 0,
          left: 0
        });
      }
      $('#myModal').modal({
        backdrop: false,
        show: true
      });

      $('.modal-dialog').draggable({
        handle: ".modal-header"
      });
    });
  </script>

The same code is generating a draggable modal while keeping background usable on the fiddle

The same is not working in my React app, can anyone please guide on this?

Upvotes: 1

Views: 1390

Answers (2)

Xameer
Xameer

Reputation: 31237

As suggested by @nithin in the comments The click handlers are registered before the DOM is ready which makes it redundant. Try moving the click handlers to componentDidMount.

componentDidMount() {    
    //modal logic goes here    
}

And the fiddle works because DOM is already initialized (Since you are not using react there) before the script executes

Upvotes: 1

Anas Mirza
Anas Mirza

Reputation: 29

Use React strap .

npm i reactstrap

<Modal isOpen={true}><Modal/>

Upvotes: 0

Related Questions