How to manually close the modal in Next.js using bootstrap 5

Incorporating Bootstrap 5.2 modals into my Next.js application has been smooth sailing so far. However, I've encountered an issue with closing the modal window after a successful backend request. To trigger the modal, I use the data-bs-toggle="modal" attribute. Following the documentation and some research, I crafted a function within my component:

 export function LoginModal() {
    const loginModalRef = useRef();

    const hideModal = () => {
        const { Modal } = require("bootstrap");
        const myModal = new Modal(loginModalRef.current);

        console.log(1,myModal,Modal)
        myModal.hide();
    };

   function sendRequest() {
        // if response success
        hideModal();
    }

    return (
        <>
            <div ref={loginModalRef} id="login-modal" className="modal fade">
                <div className="modal-dialog modal-dialog-centered">
                    <div className="modal-content">
                      <svg className="close-icon position-absolute pointer" data-bs-dismiss="modal">
                            <use xlinkHref="/images/sprite.svg#close-icon"></use>
                        </svg>
                        <div className="modal-body">
                            MyModalContetn
                            <div onClick={sendRequest}>Send</div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

Despite implementing the hide() method, the modal persists without closing, and no errors are reported.

Bootstrap has been included in _app.js as follows:

const App = ({ Component, pageProps }) => {
    // including bootstrap js
    useEffect(() => {
        require("bootstrap/dist/js/bootstrap.bundle.min.js");
    }, []);
/////

I'm seeking guidance on what might be causing this issue and how it should ideally function in my scenario. Thank you sincerely for any help provided in advance.

Answer №1

According to information from the Bootstrap Docs:

Although the Bootstrap CSS can be utilized with any framework, the Bootstrap JavaScript may not align perfectly with JavaScript frameworks such as React, Vue, and Angular [...]. There could be conflicts where both Bootstrap and the framework try to modify the same DOM element, leading to issues like dropdown menus getting stuck in the "open" position. For users of these frameworks, it is recommended to opt for a package specific to the framework instead of relying on the Bootstrap JavaScript.

In this scenario, the appropriate framework package would be React Bootstrap.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assistance requested with Javascript for an HTML dropdown menu

My question involves utilizing two HTML drop down menus. <select> <option value="">Please Select</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option ...

Iterate through an array and append individual elements to a fresh array - ensuring only a single item is present in the new

I have been working on a project where I need to call a backend API and retrieve a JSON response. I have come across various solutions, but none seem to address my specific problem. The JSON data returned from the API is structured like this: [ { ...

Having difficulty customizing Mui Accordion with Styled Utility implementation

I am having trouble overriding the CSS for an Accordion using Mui styled utility. I am trying to apply a custom CSS class, but there seems to be an underlying class that is causing issues in my code. Here is the Mui class snippet: <div class="MuiPa ...

Validation of default values in contact forms

Obtained a free contact form online and hoping it works flawlessly, but struggling with validation for fields like "Full Name" in JS and PHP. Here is the HTML code: <input type="text" name="contactname" id="contactname" class="required" role="inpu ...

What is the reason for utilizing letters as function name and parameters in JavaScript?

(function (a) { var r = a.fn.domManip, d = "_tmplitem", q = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, b = {}, f = {}, e, p = { key: 0, data: {} }, h = 0, c = ...

What is the functionality of the toArray method?

var retrieveDocs = function (db, callback) { var collection = db.collection('tours'); collection.find({ "tourPackage": "Snowboard Cali" }).toArray(function (err, data) { console.log(data); callback; }) } Is there a p ...

Invoke an ActionCreator within a different ActionCreator

Calling an ActionCreator from another file is proving to be a challenge... The products.ts file contains the ActionCreators and Reducers for Products... import { setStock } from './Store.ts'; //.... export const addProduct = (product: IProduct) ...

My approach to using this style in React involves utilizing the class attribute as follows: "class[attribute]" [Updated version 2]

When trying to customize an element based on its attribute, the process is a bit different in React compared to pure CSS. Here's an example: <div class='something' data-test='4'></div> ... .something[data-test] { bac ...

What could be causing these transformed canvases to not display fully in Chrome at specific resolutions?

fiddle: https://jsfiddle.net/f8hscrd0/66/ html: <body> <div id="canvas_div"> </div> </body> js: let colors = [ ['#000','#00F','#0F0'], ['#0FF','#F00','#F0F&a ...

What is the best way to make this eerie javascript script communicate with my webpage or another jquery file?

I've been struggling with a javascript code that enables infinite scrolling in Tumblr. It seems outdated compared to jQuery, which I'm more familiar with. I've tried integrating this script with my jQuery functions and identifying DOM eleme ...

Tips for successfully installing a package through npm

Looking to set up nest.js Using the guide provided below. https://www.npmjs.com/package/@nestjs/cli Attempted the following command $ npm install -g @nestjs/cli Encountered this error message. bash: /usr/local/bin/npm: No such file or directory Any ...

Unexpected Error: The axiosCookieJarSupport function is throwing a TypeError, functioning properly in Node.JS but not in .vue pages. What could

Struggling with a function that authenticates on a website, it runs smoothly in a basic node.js script but fails when executed from a .vue page within the NuxtJS framework. The error message received when running in the .vue page is TypeError: axiosCookie ...

Leverage the power of rxjs to categorize and organize JSON data within an

I am in need of reformatting my data to work with nested ngFor loops. My desired format is as follows: this.groupedCities = [ { label: 'Germany', value: 'de', items: [ {label: 'Berlin', value: 'Berlin ...

Error message: Uncaught TypeError - The function 'send' is not recognized in the Ajax new Request

When I called my ajax function, I encountered the following error: Uncaught TypeError: ajaxGetData.send is not a function Here is my code: <button onclick="myFunc()" class="btn btn-default">Click</button> <div id="getRes"></div> ...

Chokidar operates smoothly from the command line, but fails to function properly when invoked through the use of 'npm run'

I've implemented a script that monitors Tailwind CSS files using Chokidar. The script works perfectly when I execute the command in the CLI using chokidar 'tailwind.config.js' --initial=true -c 'npm run build-tailwind'. It successf ...

Issue with authentication when accessing Google Video API

I'm attempting to utilize the Google API provided: I have downloaded the Sample Project and followed these steps: 1) Navigate to the Project Folder named API Video 2) Run npm install 3) Set GCLOUD_PROJECT = neorisvideo 4) Download Json from the C ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

Save the output of a knex query to a variable

I'm struggling to assign the result of a select query using Knexjs to a variable. Here is my code: function getAllCategories() { let categories; categories = database.from("categories").select("category").then(function (rows) { for (let row of ro ...

How can one transform a json object into a json string and leverage its functionalities?

I recently encountered an issue with a JSON object that contains a function: var thread = { title: "my title", delete: function() { alert("deleted"); } }; thread.delete(); // alerted "deleted" thread_json = JSON.encode(thread); // co ...