Home > Software design >  How to active modal from other component using onclick (react)
How to active modal from other component using onclick (react)

Time:04-20

Need to active modal component on other component using onClick Function.

Using Bootsratp-react modal

import Modal from 'react-bootstrap/Modal'
import Button from 'react-bootstrap/Button'
import { useState } from 'react';

const UserModal=()=> {
    const [smShow, setSmShow] = useState(false);
  
    return (
      <>
        <Button onClick={() => setSmShow(true)} className="me-2">Small modal</Button>
        <Modal
          size="sm"
          show={smShow}
          onHide={() => setSmShow(false)}
          aria-labelledby="example-modal-sizes-title-sm"
        >
          <Modal.Header closeButton>
            <Modal.Title id="example-modal-sizes-title-sm">
              Small Modal
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>...</Modal.Body>
        </Modal>
      </>
    );
  }

  export default UserModal

The modal components got button, but i need his functionality in other component. The modal should be opening after onclick function and if statement.

Thank you!

CodePudding user response:

You can solve this by getting its state by parameter. Instead of inserting inside that component. That way you could reuse it in a simpler way.

example: https://codesandbox.io/embed/goofy-khorana-tdnmow?fontsize=14&hidenavigation=1&theme=dark

ps: In the example, I left the button in the component, but ideally it would be used where it is being called.

CodePudding user response:

Add data-bs-toggle="modal" data-bs-target="#example-modal-sizes-title-sm" attributes to the button on which if clicked, modal should activate.

CodePudding user response:

This is my html code of bootstrap Modal

<div className="modal fade" id="navSearchModal" tabIndex="-1" aria-labelledby="navSearchModalLabel" aria-hidden="true">
    <div className="modal-dialog">
        <div className="modal-content">
            <div className="modal-body">
                <button type="button" className="ms-auto rounded-circle modal-close-btn" data-bs-dismiss="modal" aria-label="Close">
                    <i className="fa-solid fa-xmark"></i>
                </button>
                <h5 className="modal-title text-center" id="navSearchModalLabel">Search for Products</h5>
                <input className="navbar-search-input my-3 w-100 px-2 py-2 rounded-pill" type="text" placeholder="Search..." />
                <div className='search-modal-results'></div>
            </div>
        </div>
    </div>
</div>

and this is the button which when click activates the modal

<button className="navbar-search-btn" type="submit" data-bs-toggle="modal" data-bs-target="#navSearchModal">
    <i className="fa-solid fa-magnifying-glass"></i>
</button>
  • Related