简体   繁体   中英

Accessing Bootstrap method from inside React app

I'm trying to use Bootstrap's .modal() method described here inside of a React app to display a modal. Here's what I'm run:

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.modal = React.createRef();
  }

  componentDidMount() {
    this.modal.modal()
  }

  render() {
    return (
      <div
        className="modal fade"
        ref={this.modal}
      >
        //some stuff
      </div>
    );
  }
}

export default Modal;

For some reason React is unable to access the .modal() in this.modal , although the latter object points to the correct DOM element. Any ideas on how can I run that method?

You have to import some dependencies to be able to use .modal() .

From the docs

Many of our components require the use of JavaScript to function. Specifically, they require jQuery, Popper.js, and our own JavaScript plugins. Place the following s near the end of your pages, right before the closing tag, to enable them. jQuery must come first, then Popper.js, and then our JavaScript plugins.


On your index.html add the following scripts right before your body 's closing tag.

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

Then on your Modal component, change your componentDidMount to

componentDidMount() {
  window.$(this.modal.current).modal();
}

编辑 upbeat-wing-6sqxo


It seems that you want to automatically open the modal when component is mounted; using React Bootstrap you can easily achieve this by using theModal component and pass true as show prop.

...
import Modal from "react-bootstrap/Modal";

class MyModal extends React.Component {
  state = {
    show: true
  };

  render() {
    return <Modal show={this.state.show} />;
  }
}

编辑sharp-bouman-ee74e

If you have the option to use another library, I suggest Reactstrap as it has some nice HoCs that will make integration a breeze.

import React, { useState } from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';

const ModalExample = (props) => {
  const {
    buttonLabel,
    className
  } = props;

  const [modal, setModal] = useState(false);

  const toggle = () => setModal(!modal);

  return (
    <div>
      <Button color="danger" onClick={toggle}>{buttonLabel}</Button>
      <Modal isOpen={modal} toggle={toggle} className={className}>
        <ModalHeader toggle={toggle}>Modal title</ModalHeader>
        <ModalBody>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </ModalBody>
        <ModalFooter>
          <Button color="primary" onClick={toggle}>Do Something</Button>{' '}
          <Button color="secondary" onClick={toggle}>Cancel</Button>
        </ModalFooter>
      </Modal>
    </div>
  );
}

export default ModalExample;

Otherwise, check Devtools and/or your logs to make sure Bootstrap and it's JS dependencies are loading properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM