What is the best way to ensure that a Mantine burger closes once a link is clicked?

Is there a way to automatically close the Mantine burger after selecting a navigation choice in the modal? It appears that the burger does not close automatically (due to the x icon remaining visible). My setup includes NextJS with Mantine & react-icons.

    export default function HeaderMiddle({ links }: HeaderMiddleProps) {
      const { colorScheme, toggleColorScheme } = useMantineColorScheme();
      const dark = colorScheme === 'dark';

      const [opened, { toggle, open, close }] = useDisclosure(false, {
        onOpen: () => burgerClick(),
        onClose: () => closeAllModals(),
      });
      const [active, setActive] = useState(links[0].link);
      const { classes, cx } = useStyles();

      const items = links.map((link) => (
        <a
          key={link.label}
          href={link.link}
          className={cx(classes.link, {
            [classes.linkActive]: active === link.link,
          })}
          onClick={(event) => {
            event.preventDefault();
            setActive(link.link);
          }}
        >
          {link.label}
        </a>
      ));

      const burgerItems = links.map((link) => (
        <a
          key={link.label}
          href={link.link}
          className={cx(classes.link, {
            [classes.linkActive]: active === link.link,
          })}
          onClick={(event) => {
            event.preventDefault();
            setActive(link.link);
            closeAllModals();
          }}
        >
          {link.label}
        </a>
      ));

      const burgerClick = () => {
        openModal({
          title: 'Subscribe to newsletter',
          children: <>{burgerItems}</>,
        });
      };

      return (
        <Header height={56} mb={120}>
          <Container className={classes.inner}>
            <Burger
              opened={opened}
              onClick={toggle}
              size="sm"
              className={classes.burger}
            />
            <Group className={classes.links} spacing={5}>
              {items}
            </Group>

            {/* <MantineLogo size={28} /> */}

            <Group spacing={0} className={classes.social} position="right" noWrap>
              ...
            </Group>
          </Container>
        </Header>
      );
    }


Any assistance on this matter would be greatly appreciated.

next: 12.1.5 @mantine/core: 4.2.12

Answer №1

By selecting the link and invoking the close method of useDisclosure, the state of "opened" will switch to false. Since the burger state is tied to the value of "opened", closing the burger will also set it to false.

const burgerItems = links.map((link) => (
    <a
      key={link.label}
      href={link.link}
      className={cx(classes.link, {
        [classes.linkActive]: active === link.link,
      })}
      onClick={(event) => {
        event.preventDefault();
        setActive(link.link);
        closeAllModals();
        // Setting opened to false (closing Burger)
        close()
      }}
    >
      {link.label}
    </a>
  ));

Answer №2

Stumbled upon a useful resource for you! Check out the Mantine Doc and look for the 'Responsive header' section - it works flawlessly when you click on any of the burger items.

Just follow the provided codes and everything should work smoothly!

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

Progressing in a connected sequence of changes on a linear graph with distinct points and a pause

A jsfiddle has been created here. Looking to move a circle along a sine wave graph, triggered by a click event. The circle should stop at specific x and y value pairs on the graph before moving to the last point and looping back to the first (ideally unti ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

JSONP OpenWeather API

I've been trying to access and retrieve weather data from OpenWeather using their API, but unfortunately, I'm facing some difficulties in getting it to work. It seems like there might be an issue with the way I am fetching the JSON data. To quer ...

When hovering over slick text, it becomes hidden because of non-responsive CSS. Are there any solutions to make it responsive?

I can't seem to get the on-hover dates to appear, even though they are rendered when inspecting the page. I suspect it could be related to a responsive CSS issue or class breaking. How can I resolve this? https://i.stack.imgur.com/jyEJb.png https:// ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

How can one include a URL as a "URL parameter" when using Express?

In my Node.js application, I've set up a router to listen for requests at api/shorten/: router.get('api/shorten/:longUrl', function(req, res, next) { console.log(req.params.longUrl); } When I enter something like: http://l ...

Looking for guidance on utilizing pushState and handling onpopstate events?

By using ajax, I am able to load specific page content without refreshing the entire page. In order to make the back button functionality work, I utilize pushState and onpopstate as shown below: function get_page(args){ .... $.ajax({ url ...

Obtain text content using JQuery and AJAX rather than retrieving the value

I am struggling with a dynamic table that needs to perform calculations before submitting, requiring the presence of values. However, I want to submit the text from the options instead of the values. Despite trying various approaches, none of them seem to ...

What is the method for extracting a value that is being displayed beneath a text in a React component using Selenium?

Attached is a screenshot showcasing HTML tags: Our task is to display the 3 within react-text. Here's the code snippet I attempted: WebElement MyText = driver.findElement(By.xpath("(//div[@class='badge-number'])[6]")); JavascriptExecut ...

The state of the UI is not updating to reflect the selected item in React Native

I'm working on a component that needs to display all ingredients from my database, but I'm encountering issues with the state not updating as expected. Here are the variables: const image = require('../../assets/backgroundMeal.png'); ...

Leveraging React useEffect for retrieving data and managing component behavior

Having trouble querying data, setting it to state with useEffect, and rendering the results? I've tried a few things but only see changes when state is updated. Any advice would be greatly appreciated. Thank you in advance. useEffect // fetchCamp ...

Issue with locating JavaScript controller in Angular HTML file [Node.js/Angular]

Here are all the files and folders in my project located within the same directory. If you want to check out the project on Github, you can find it here: https://github.com/JohnsCurry/learnAngular. Just to confirm, they are all in the same folder. Unfortu ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

Leverage Angular to highlight updated items within a list

My goal is to synchronize data, so I have a data object that holds the current state. Whenever this state changes, I want to mark the object with an attribute for filtering purposes during syncing. Here is the structure of the object: data = { type1: [ ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...

Is the value incorrect when using angular's ng-repeat?

Currently iterating through an array nested within an array of objects like this: <div ng-repeat="benefit in oe.oeBenefits"> <div class="oeInfo" style="clear: both;"> <div class="col-md-2 oeCol"> <img style="he ...

Error loading resource: The server returned a 404 status code indicating the requested resource was not found in the Node.js socket.io

My challenge involves setting up a server with Node.js and socket.io which starts perfectly fine. However, when I attempt to access my server's site through the browser, it shows "Cannot Get /" and in the console, an error appears saying "Failed to Lo ...

Tick the box to activate the ability to uncheck multiple boxes when there are already a certain number of boxes checked

I am currently developing a multiple-choice form in my MVC5 app and I am struggling to find a way to disable unchecked boxes once a specific number of boxes have been checked. For example, if 3 out of 5 boxes are checked, the remaining 2 should be disabled ...

Issue with Mouse Hover not functioning properly across various 3D objects

Trying to create a 3D line chart? Check it out Here Currently, the points and lines are working fine. However, I only want to detect mouse hover on the points (spheres) and not on the lines or grid. To achieve this, I have segregated all elements into dif ...