Unable to establish a hyperlink to specific section of page using MUI 5 Drawer

When attempting to link to a specific part of my first page upon clicking the Shop button in the navigation Drawer, nothing happens:

https://i.stack.imgur.com/FUQCp.png

This snippet shows the code for the MUI 5 Drawer component:

    <Drawer
      anchor="left"
      open={open}
      onClose={() => setOpen(false)}
      PaperProps={{
        sx: {
          background: "linear-gradient(to top, #9C685B44, #9C685Bff)",
        },
      }}
    >
      <IconButton onClick={() => setOpen(false)}>
        <ChevronLeftIcon sx={{ color: "white" }} />
      </IconButton>
      <Divider />
      <List>
/////////////////////////////////
        <ListItem>
          <Button
            // Linking to Products Section
            href="#products"
            startIcon={<PhoneAndroidIcon />}
            sx={{
              color: "white",
              fontFamily: "Montserrat",
            }}
          >
            Shop
          </Button>
        </ListItem>
//////////////////////////////
        <ListItem>
          <Badge color="error" badgeContent={badgeNumber}>
            <Button
              startIcon={<ShoppingCartIcon />}
              sx={{
                color: "white",
                fontFamily: "Montserrat",
              }}
            >
              Cart
            </Button>
          </Badge>
        </ListItem>
      </List>
    </Drawer>

In the corresponding section, I have included an id with the value of "products" on the container:

<Container maxWidth="xl" id="products">
   ...
</Container>

The issue persists even when using the anchor tag.

Any suggestions on how to resolve this?

Answer №1

If you want to handle this situation, you can utilize the scrollIntoView function along with History.pushState(). Simply remove the href attribute from your Button component and use its onClick method to trigger the following action:

// Specify the section names (e.g., 'products') as id
// URL is optional and defaults to the document's current URL if not provided

const onNavClick = (event, id, url) => {
    let element = document.getElementById(id);
    event.preventDefault();
    element.scrollIntoView();
    window.history.pushState(id, id, url);
}

You can explore additional options that can be passed into scrollIntoView by referring to the link mentioned above for more details.

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

Retrieve the child element that is being clicked

Alright, I'm facing a little issue here (it seems simple, but I just can't seem to crack it)... Let me paint the picture with a snippet of HTML code below: <!-- New Website #1 --> <!DOCTYPE html> <html style='min-height:0px; ...

Unable to extract a particular value from a JSON data structure

This situation has been on my mind for a good couple of hours now. I have this json object with example values like so: { "events": [ { "id": 64714, "live": false, "start": "1399117500", "league_ ...

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

The H1 tag fails to appear on the webpage

I can't figure out why my H1 is not visible. It seems to be hidden by a div. What's strange is that the parent div is visible when I change the background color to something other than transparent. Even an input tag within the same div displays c ...

Elements with fixed positions in CSS overlapping one another

Hey there, I'm working on a navigation bar and using Jquery to resize elements for better website aesthetics. Instead of a traditional horizontal list, each button is created individually with images: <a href="#" class="button" id="home"><im ...

Angular tutorial on splitting a JSON array

I am looking to extract a portion of a JSON array in Angular. The array looks like the one in the image below.https://i.stack.imgur.com/w0hqC.png Below is the code snippet: export class AppComponent { color: string = 'green'; public stocklis ...

Removing all table rows except one in Jquery

I currently have this code in my view: <script> $(document).ready(function() { $("#add_instruction").click(function(){ $("#instructions").append("<tr><td></td><td><input type='text' name='rec ...

Is the JSON data not matching the file's content during validation?

After thorough testing, my JSON data appears to be functioning correctly with regular content. Here is a sample of the working JSON: Working Json { "language": "XYZ", "content": { "GEN": "this is test& ...

Stretch element to reach the edge of the container

I need help with positioning an input and a textarea inside a container that has a height of 52.5vh. I want the textarea to start right below the input and expand all the way to the end of the container. How can I achieve this layout? Both elements should ...

"What is the best way to apply multiple filters to an array in a React

Is there a way to incorporate dropdown menus along with search text input for filtering an array in React? I would like to give users the option to select a location and then search for specific results within that location. Any suggestions on how to ach ...

Summernote - When validating text, it is shown as raw HTML

I have integrated Codeigniter with Summernote on the frontend. In a form, if certain fields are left empty, the same page reloads for validation checking. The JavaScript and CodeIgniter code I am using is as follows: $(window).load(function(){ &l ...

Is there a way to keep my fixed footer container from moving while zooming in and out on a webpage

Is there a way to prevent the bottom text from shifting when zoomed in or out on the page? The rest of the content remains stable, but due to using position:absolute for this section to stay at the bottom of another div (content), it causes movement. #con ...

Issue: The SupabaseClient.auth.getSession function is not recognized as a valid function, causing an error when using Supabase with Next

I am currently utilizing the Supabase auth helper package for my project, integrating it with React and Next. Upon starting the page, an error message immediately pops up indicating that I have not called the supabaseClient.auth.getSession() method. This h ...

Issue: A file that has been uploaded completely ignores the req.on() method in NodeJS

I am currently using MEAN.IO to create a web application. Right now, I am working on implementing an image uploader feature. I have decided to use angular-file-upload for this purpose, and it seems to be functioning well. However, I am facing an issue on ...

aligning a floating image vertically

One issue I am facing in my UI is that I have buttons with images floating next to text. While the setup works well, I am struggling to vertically align the image with the text. I've experimented with various solutions including using vertical-align: ...

"Repeating SignalR Messages: Issue of Duplication when Stopping and Restarting

Whenever I stop and start the connection, messages sent to the client by the hub are duplicated. If I follow this sequence: $.connection.hub.stop() $.connection.hub.start() {...} and a message is sent from the server hub to the client, it is initially re ...

Customize Text Style in Material-UI and Next.js

Hi! I'm currently working on a new web project and looking to switch the font to Oswald (). My tech stack includes NextJS with MUI for the components. I've been struggling to find a solution on how to make this change successfully. Any guidance ...

Tips for implementing xpath in module.exports with mocha javascript

Currently, I am utilizing mocha in conjunction with Node.js and have encountered a challenge. In my scenario, I need to use the XPath defined in one test file (verification.js) and apply it in another file (test.js). The issue arises from the fact that the ...

The <nav> and <section> elements are not appearing on the page

Website: CSS: Hello there! I am experiencing an issue where the nav and section elements are not displaying on my website. They seem to only show the height and background-color attributes. Interestingly, they appear correctly on my old Firefox version ( ...

Tips for creating a web page with rounded screen corners, similar to those on an Android smartphone

I am looking to create rounded screen corners on a website similar to those found on an Android smartphone. Here is an example of what I am trying to achieve: I have searched for tutorials online but haven't had much luck finding the right solution. ...