Guide on programmatically closing a Bootstrap 5 offcanvas in Next Js

I have integrated Bootstrap 5 into my NextJs app by installing it using the command: npm install bootstrap and then importing the necessary files into my project via _app.js as shown below:

import 'bootstrap/dist/css/bootstrap.css'

...

useEffect(() => {
    import("bootstrap/dist/js/bootstrap");
}, []);

The issue I am facing is that when I open the offcanvas modal and click a link from there, the offcanvas remains open even after the page changes. How can I programmatically close the offcanvas when the pathname changes and only if the offcanvas is active? Thank you for your help.

Note: I am not using react-bootstrap

Answer №1

Recently I encountered a similar issue, but here is how I managed to resolve it.

Firstly, it appears that the way you are importing bootstrap into your nextjs app may not be correct, but if it's working for you then that's fine. However, I suggest importing bootstrap into your nextjs app like this:

useEffect(() => {
    typeof document !== undefined
      ? require("bootstrap/dist/js/bootstrap")
      : null;
  }, []);

Let's dive straight into creating the solution without making this too lengthy. Firstly, you need to create a custom function to close the offCanvas when clicking on a link.

const topicRef = useRef(null);

const closeOffCanvas = (event) => {
    event.stopPropagation();
    const bootstrap = require("bootstrap/dist/js/bootstrap");

    var myOffcanvas = topicRef.current;
    var bsOffcanvas = bootstrap.Offcanvas.getInstance(myOffcanvas);

    bsOffcanvas.hide();
  };

Now, create your link in this manner and invoke the function we just created:

<Link href={`/article/18004/close-bootstrap-5-offcanvas-in-next-js`} passHref>
 <a href="#" onClick={closeOffCanvas}>navigate to page then close offCanvas</a>
</Link>

I hope this explanation helps you with your issue.

Answer №2

After some trial and error, I found a solution that worked for me: I realized that importing individual bootstrap modules instead of all modules was causing the global window.bootstrap object to not be set. To address this issue, I created a file called utility/bootstrap.ts to properly initialize my subset of bootstrap:

import type {
  Alert,
  Button,
  Carousel,
  Collapse,
  Dropdown,
  Modal,
  Offcanvas,
  Popover,
  ScrollSpy,
  Tab,
  Toast,
  Tooltip,
} from 'bootstrap';

export async function initBootstrap(): Promise<void> {
  // Code block 
}

To ensure proper type imports, it is necessary to install @bootstrap/types. Then, in the relevant component (in my case, Next Js' _app.tsx), I initialized bootstrap asynchronously using the utility function:

export default function MyApp({ Component, pageProps }: AppProps) {
  // Code block
}

This approach enabled bootstrap to identify the offcanvas correctly without creating duplicates, as demonstrated below:

export function Header() {
  const offcanvasElRef = useRef<HTMLDivElement>(null);
  // Code block
}

Answer №3

To add the import, simply follow these steps:

useEffect(() => {
    import("jquery/dist/js/jquery");
  }, []);

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

Having trouble changing a state from a class component to a function component in React

I've been updating my React projects by converting all my classes to functions. However, I encountered an issue where ESLint is reporting a parsing error in my code. Oddly enough, if I remove just one line, the error disappears. Here's the snippe ...

Developing a pop-up feature that triggers upon clicking for a miniature rich text editing

Looking to integrate the Tiny rich text editor into my code. Check out the TextEditor.js component below: import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorCha ...

How can you fix the warning message in Next.js that says "Expected server HTML to include a matching <header> within <body>"?

I came across a warning message in my Nextjs application stating "Expected server HTML to contain a matching ." It seems like there is a discrepancy between the expected HTML structure and the actual content served by the server. How can I resolve this iss ...

Is it possible to use async in the onChange handler of a React event?

Can async be used to pause execution until a function completes within an onChange event? Here is an example: const onChange = async (e) => { console.log(current[e.target.name]); await setCurrent({ ...current, [e.target.name]: e.targe ...

Easiest method for creating a distinct identifier for a form-inputted value in React

My goal is to extract the value from the input field, generate a unique id for it, and then pass both the name and id to the addFolder() function. The object will then be added to the end of the state's folders array. My main challenge lies in creatin ...

Enhance user experience by customizing login functionalities in Meteor using React: Integrate personalized

Currently, I am utilizing account-ui to incorporate a drop-down login feature in Meteor. However, I have encountered an issue where I am unable to expand user sign-up functionality to include First and Last Name fields. This is because Meteor account ui on ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

Efficient method to retrieve my app's version in a React Native environment

I have a React Native app that I created using the command react-native init. I want to define a global constant for my APP_VERSION so that I can access it in the Authentication/Login screen. Currently, the only place I see this variable is in my package. ...

Adding a <link> tag with a specific onload attribute in the <head> using Next.js

While working on a Next.js project, I am trying to include the following HTML content within the <head>: <link href="..." rel="stylesheet" media="print" onload="this.media='all'" /> The code I ...

Guide on implementing lazy loading with data-grid material-ui

I encountered an error when trying to import the data-grid using lazy loading. const DataGrid = lazy(async () => await import('@material-ui/data-grid')) I have successfully imported other material-ui components without any issues, but for so ...

Using TypeScript, Material UI introduces a new property to the primary object on the palette

Experimenting with the customization of MUI v5 theme has been a fun challenge in my current project. I have successfully tailored the theme to suit my requirements so far, but now I am faced with the task of adding a new property to the primary object defi ...

When filtering an array in JavaScript, ensure to display a notification if no items match the criteria

In React/Next, I have an array that is being filtered and sorted before mapping through it. If nothing is found after the filters run, I want to display a simple message in JSX format. The message should be contained within a span element. Here is the str ...

Transform routeParams from string to numerical format

Currently, I am working on a straightforward project where I need to retrieve data based on the id number using "routeParams". However, I encountered an issue because the "routeParams" is in string format and I actually need it to be converted to a numbe ...

React Native Child Component State Update Issue

In my code, there is a Child component that triggers a function in the Parent component. However, when the function is triggered, an error related to the setState method is thrown. Issue with Promise Rejection (id: 0): The '_this12.setState' i ...

Obtain cell information when clicking on a specific field within a material-table

import MaterialTable from "material-table"; import ShipmentContext from "../context/ShipmentContext"; const ItemsTable: React.FC = () => { const shipmentcontext = useContext(ShipmentContext); const { filtered } = shipmentcontex ...

Is it possible to alter the style of a child element using the root component in material UI?

Material UI provides a component that I am using. When I apply my style as a classname to the component using withStyles, it styles the entire component. However, I want to change the style of a specific child element within the component, not the root. T ...

Tips for expanding the count and confirming whether the user is a fan using node.js?

I am looking to update the like and dislike count in videoSchema based on the likedislikeSchema. Can you provide guidance on how to achieve this? For example, when a user likes a video, the like count should be incremented in videoSchema, and the videoId ...

Utilizing lazy loading to import local JSON data in Next.js

I currently have a JSON file stored locally in my project, which is an array with over 200 items. For example, the file is named data.js const data = [ { title: 1 }, { title: 2 }, ... { title: 200 } ]; Here is how I import it i ...

Here's a guide on customizing the appearance of the date picker in NativeBase components for React Native by

Is there a way to show icons while using the date picker component from the Native Base UI library? ...

Create a music player application using the React context API

Here is a code snippet for implementing a music player using context: import React from 'react'; import { BarSongTitle, BottomBar, Button, PlayList, Song, SongTitle, } from './styles.js'; import { songList } from './con ...