Go to a different page section using MUI 5

I am currently working on a React application and I want to implement a functionality where pressing a button on my Nav Bar will navigate to a specific section on the first page. To achieve this, I have created an onClick function for my button:

const onNavClick = (e, id) => {
  let element = document.getElementById(id);
  e.preventDefault();
  element.scrollIntoView();
};

...

<Button
  onClick={(e) => onNavClick(e, "products")}
  ...
>
  Shop
</Button>

I have also assigned an id to the element that I wish to navigate to.

While everything works as expected on the main page where the element is present in the DOM, I encounter an issue when trying to access it from another page using the Nav button. The error message I receive is:

Cannot read properties of null (reading 'scrollIntoView')

Is there a way for me to access that element from other pages and navigate to that specific section on my first page?

Answer №1

If you attempt to scroll to an element that is not present on the page, it will not work. For more information, refer to the documentation.

The Element interface's scrollIntoView() function scrolls the containing parent of the element so that the element itself becomes visible to the user.

When it comes to navigating between pages, there are several options available.

You can utilize a Link component from MUI:

<Link href='#'>Link to another location</Link>

If you are working with Next.js, you have access to their in-built router:

import { useRouter } from 'next/router'
const router = useRouter()
router.push('/homepage')

An alternative commonly used router is react-router:

import { useNavigate } from "react-router-dom"
let navigate = useNavigate()
navigate('/homepage')

If your intention is to navigate to a specific page and then scroll to an element within that page, you can achieve this by passing relevant data and handling it accordingly in the destination page.

Example utilizing Next.js:

Include data as a query parameter:

import { useRouter } from 'next/router'
const router = useRouter()

// Provide some form of reference to the element you wish to scroll to
router.push({
    pathname: '/homepage',
    query: { scrollTo: element }
})

In the /pages/homepage directory, examine the query parameters and manage them appropriately:

import { useRouter } from 'next/router'
const router = useRouter()
let element
if (router.query?.scrollTo)
{
    element = router.query.scrollTo
    // Perform scrolling to the specified element
}

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

Console not displaying array output

Context: Currently, I'm in the process of developing an application that utilizes AJAX to fetch PHP arrays encoded into JSON format for dynamically constructing tables. However, I've encountered an issue where despite having no compilation errors ...

Submitting information to a server

I have a simple Angular 6 app with follow and unfollow buttons. When you click follow, the number increases. I want to save these follower numbers to a JSON server. Here is the link to the JSON server documentation: JSON Server Documentation To see a dem ...

Ways to switch the visibility of a specific thumbnail

Our team has created a new app that showcases all the videos in our channel. Users can browse through thumbnails and click on one to view the related video, instead of viewing all videos at once. Angular Code $scope.isvideoPlaying = false; $scope.displ ...

Move files in Node.js without removing the original source directory

Currently, I am facing an issue while attempting to transfer files from one directory to another using the mv module. The problem arises when the files are successfully moved, but the source directory is automatically deleted. My intention is for only the ...

Building New Web Pages with Express in Node.JS

I want to dynamically generate a new page on Node.JS with Express upon user form submission. Here is my initial approach, but it's not working as expected: var app = require('express')(); var server= require('http').createServer(a ...

Connecting a specific entry in a data table with a corresponding web address

I have been working on a vue component that utilizes vue-tables-2. You can find the functioning example here. My goal is to link the edit href url to the entire row rather than just the edit cell. I attempted to achieve this using vanilla javascript by a ...

When executing npm run dev, the Next/image component encounters an error stating that the "width" property is missing and required

When I start my Next.js app with npm run dev, the Image component triggers an error stating that the "width" property is missing. In order to resolve this issue and get the app running properly, I had to define both width and height as inline attributes f ...

How come flex won't let me rearrange an image?

.nav { height: 500px; } .navphoto { height: 500px; display: flex; justify-content: flex-end; } <div class="nav"> <img class="navphoto" src="images/navphoto.jpg"> </div> Just wondering why I can't seem to move an image, bu ...

The following stage in the form fails to load

I've been experimenting with splitting my questions into different "pages" to display various groups of inputs. The transition from the first question to the second works fine for me, but I encounter an error when moving from the second to the third q ...

What is the best method to override the CSS transition effect with JavaScript?

I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animati ...

Is it possible to make any object reactive within Vuex?

Seeking ways to enhance the sorting of normalized objects based on a relationship. Imagine having an application that requires organizing data in a Vuex store containing multiple normalized objects, like this: state: { worms: { 3: { id: 3, na ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...

Ways to retrieve the most recent state in a second useEffect call?

Currently, I am encountering a situation where I have implemented two useEffect hooks in a single component due to the presence of two different sets of dependencies. My challenge lies in the fact that even though I update a state within the first useEffec ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

Which option is better: installing plotly.js or plotly.js-dist using npm?

When it comes to plotly.js and plotly.js-dist, what exactly sets these two packages apart from each other? Notably, the installation instructions for plotly.js on npmjs.org specify running 'npm install plotly.js-dist' - why is this necessary? W ...

Unable to create a flawless circle using Canvas

No matter how hard I try, drawing a perfect circle seems impossible for me. Every time I attempt it, all I manage to create is an ellipse. Check out this code snippet I put together as an example: function canvasClicked(number) { var c = "canvas" + nu ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Encountering an 'Unknown provider' error while running a unit test with AngularJS and Jasmine

I am facing an issue while writing a unit test for a controller in my application. Jasmine is showing an 'Unknown provider' error related to a provider I created for fetching template URLs. This provider is injected into a config function that is ...

Outside drop shadows in CSS3 creates an interesting visual effect by giving

I am currently using the following CSS styling for a list of li items. border: 1px solid black; border-radius:10px; box-shadow: 8px 8px 4px #666; -o-box-shadow: 10px 10px 5px #888; -icab-box-shadow: 10px 10px 5px #888; -khtml-box-shadow: 10px 10px 5px #8 ...

Dynamic count down using JavaScript or jQuery

I am looking for a way to create a countdown timer that I can adjust the time interval for in my database. Basically, I have a timestamp in my database table that might change, and I want to check it every 30 seconds and update my countdown accordingly. H ...