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

Rails 4 does not properly handle the execution of Ajax responses

Currently, I am incorporating ajax functionality within my Rails application. Within the JavaScript file of my application, the following code snippet is present: $('#request_name').on('focusout', function () { var clientName ...

Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the M ...

I am encountering an issue where my codeigniter controller is unable to load my model

Below is the code for my controller: defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('User_model') ...

Spin a child element by clicking on its parent component

I am looking to create a unique animated effect for the arrows on a button, where they rotate 180 degrees each time the button is clicked. The concept involves rotating both sides of the arrow (which are constructed using div elements) every time the con ...

What is the best way to automatically resize a React Material Slider component?

Is there a way to set the slider to automatically adjust its width? Currently, I can only specify a fixed width in the css or leave it blank, resulting in a zero-width slider. What I need is to have the label on the left (with variable size) and then the ...

Animating the navbar with CSS transitions

Seeking advice on adding a transition effect to my navbar. Specifically, I'd like to have a colored background appear below each link when hovered over. For example, when hovering over "HOME," a yellow color should display, and it should disappear whe ...

The reason for the lack of auto complete functionality in this specific Bootstrap example remains unclear

I've been attempting to implement an auto-complete dropdown feature with dynamic data, but I'm facing an issue where no suggestions are displayed in the dropdown. I found this example on Datalists: https://getbootstrap.com/docs/5.1/forms/form-con ...

Delete the top row from the table

After extensive searching on various websites, I am still unable to resolve my html or CSS issue. An unexpected line is appearing above the table here. Here's the code snippet that is causing trouble: <table border="0" width="840" cellspacing="0" ...

Aligning columns next to one another using flexbox in a centered manner

I am attempting to create a layout with 3 columns, but I want any extra columns beyond a multiple of 3 to be centered instead of aligned left. While I have made progress, the issue I'm facing is that the additional columns are not centered relative t ...

"Exploring the functionalities of repeat and minmax in tailwind - a comprehensive guide

Hey there, I have a question about using repeat and minmax in grid with Tailwind CSS. I tried the following code but it didn't work as expected. const DetailedAssetCard = () => { return ( <div className=" bg-gray-100 rounded-lg grid ...

New React Component Successfully Imported but Fails to Render

I've encountered issues with the code I'm currently working on. Dependencies: React, Redux, Eslinter, PropTypes, BreadCrumb Within a view page, I am importing components from other files. The current structure is as follows: import Component ...

Different Techniques for Defining Functions in an AngularJS Controller Using the controllerAs Method

When using the 'controller as' approach instead of $scope, I am encountering issues with method calling from HTML. My question is, how many ways are there to declare and call functions using this approach? First: (For executing something initial ...

ajax is unable to decode a JSON string from a GET request

Currently, I am leveraging angularjs to retrieve userId, userTitle, and userComment from a form. These values are then sent to a PHP page from the controller for communication with a server. Everything works well when sending integers, but I face an issue ...

Is it possible to access a component's function from outside an ng-repeat in Angular 1.5?

Recently delved into learning Angular 1.5 components and testing out some fresh concepts, however, I'm struggling to wrap my head around this particular issue: Here's the code snippet from my Main: angular.module('myapp',[]) .contr ...

Looking to create a loop that continues as long as a JSON dataset remains assigned to a specific variable

I've been trying to retrieve JSON data, but I seem to have hit a snag. I'm not sure where I went wrong or how to correct it. [ { "userId": 1, "title": "A", "body": "B" }, { "userId": 1, "title": "C", "body": "D" }, { "userId": 2, "title": "E", " ...

How to effectively use graph paper with both major and minor grids in the background?

Looking to create a 100px by 100px image in Inkscape with major lines every 100px and minor lines every 10px. This will help verify viewport size when used as a repeating background. What's the best approach for this? Thinking of using #888888 for ma ...

What is the best way to create a menu in JavaScript that includes a variable declaration?

Here is the menu I've created: <a id="page1" href="" onclick="var = page1">Home</a> <a id="page2" href="" >About us</a> <a id="page3" href="" >Services</a> <a id="page4" href="" >Partners</a> <a ...

Retrieving and showcasing precise data from an onClick event on one page to another in React

Currently, I am engrossed in a react project where my aim is to extract particular data from a clicked button/profile and then showcase it on another page. Here's what I have so far. A list of profiles belonging to various celebrities are being displ ...

What is the best way to display "No results found" in Mat-select-autocomplete?

I am working with the mat-select-autocomplete for a multiselect dropdown. When searching for values that are not in the list, I want to display a message saying "No results found". Can someone please help me achieve this? Link to Code ...

oidc-client.js throws an error stating that no authority was provided

As someone new to SSO, I have recently been immersed in a project that utilizes OIDC. My focus has been on using oidc-client to address the issues at hand. Below are my settings (with some details redacted for privacy). var mgr = new Oidc.UserManager({ ...