Can a user be redirected from one page to the bottom of a different page using React?

Is there a way to redirect from one page to another in React and automatically scroll to a specific section when a button is clicked?


const navigatePage = () => {
   if(window.location.pathname !== '/target-page'){
     window.location.assign(TargetPageLink());
     window.scrollTo({ top: document.getElementById('specific-section').offsetTop, behavior: 'smooth' });
   }
}


<div onClick={navigatePage} className={classes.button} style={{display: showButton ? 'block' : 'none',}}>
    ...
</div>

The desired destination on the second page can be identified by an HTML element.

<div id="specific-section"></div>

I am currently facing the issue where the window scrolls first and then redirects to the other page. Is there a way to reverse this order or any alternative methods to achieve the same outcome?

I am open to suggestions and ideas that can help me achieve the desired functionality seamlessly.

Answer №1

To address your issue, consider utilizing anchors. Simply assign an id to the element you want to scroll to. For instance:

<div id="bottom" />

Subsequently, you can reference it within your URL: https://example.com/products#bottom. By changing window.location to this URL upon button click, the specified part of your HTML element will be displayed in the window.

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

Creating a React Material-UI dropdown with a customizable display value that differs from the selected option

I am working on creating a dropdown that shows multiple buttons for selection and a display value that is independent of the items in the dropdown, like this: https://i.stack.imgur.com/zgfu4.png For example, the user can choose different scales for a cha ...

Incorrect date generated by Moment.js from Unix timestamp

Is there a way to store unixtime as a Moment.moment state? Using moment(timestamp) seems to provide a different date. const [date, setDate] = useState<moment.Moment | null>(null); const timestamp = Math.floor(date.getTime() / 1000); setDate(m ...

Troubleshooting issue with the spread operator and setState in React, Typescript, and Material-ui

I recently developed a custom Snackbar component in React with Material-ui and Typescript. While working on it, I encountered some confusion regarding the usage of spread operators and await functions. (Example available here: https://codesandbox.io/s/gift ...

Creating a vertical swiper in React is a simple task that can be accomplished by adjusting

I am looking to create a homepage where I can swipe through one post at a time in mobile view. I have experimented with React Swiper, but it only allows horizontal swiping of posts. I would like to swipe posts vertically instead. Any suggestions on how t ...

What's the trick to efficiently managing multiple checkboxes in an array state?

I have a lengthy collection of checkboxes that is not well optimized. I am trying to obtain the checked ones and store them in an array state. However, I am uncertain about how to handle this situation and I would appreciate some assistance. It should also ...

Deactivate hover effects and media queries for Material UI controls in all states

Since I am using a touch-capable monitor, I noticed that hover styles are not showing up on any controls. Specifically, when I hover over a Material UI button, I see the following styles: https://i.stack.imgur.com/uwBpt.png Is there a way to disable all ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

Obtaining the data from the React material-UI Autocomplete box

I have been exploring the React Material-UI documentation (https://material-ui.com/components/autocomplete/) and came across a query. Within the demo code snippet, I noticed the following: <Autocomplete options={top100Films} getOptionL ...

What is the best way to align the title of a Dialog in Material UI to

Is there a way to center the DialogTitle (Material UI) using my code snippet below? <Dialog open={this.state.open} titleStyle = {styles.Dialog} title='Title centered please!' actions={standardActions} onRequestClose={this.handle ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

Having trouble adding a custom font with override to MuiCssBaseline in react-admin, the @global @font-face seems

I am attempting to integrate the NotoSansSC-Regular.otf font from Google into my react-admin application as the default font for simplified Chinese text. I have managed to make it work by including the fonts in the root HTML file using CSS, like this: ty ...

Is it possible to utilize target="blank" in an external link when working with MDX?

For my latest project, I am developing a blog using NextJS and MDX. One of the features I would like to implement is opening external links in a new tab by adding a target="_blank" attribute. In typical Markdown syntax, I usually achieve this by using [wo ...

Integrating domain name into a post request using React

Currently, I have a frontend (react, Node.js) and a backend Springboot hosted on the same remote hosting service at . The frontend and backend are placed in different environments but function well individually. I connected my frontend to a domain and up ...

Attempting to use a string as an index for the type `{ firstName: { inputWarning: string; inputRegex: RegExp; }` is not allowed

const checkRegexSignUp = { firstName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, lastName: { inputWarning: "only letters", inputRegex: /^[a-z ,.'-]+$/i }, } const change = (e: ChangeEvent<HT ...

Utilizing the change of state in one useEffect to prompt the execution of another useEffect

While working on a project, I decided to incorporate a wysiwyg style editor. I came across a video on YouTube showcasing a Reddit clone that had the feature integrated using Editor JS. As I delved into the code, I noticed an interesting use of useEffect tr ...

Tips for decreasing the width of a Grid component in React using MUI

Is there a way to adjust the width of the initial Grid element within Material UI, allowing the remaining 3 elements to evenly occupy the extra space? see visual example Would modifying the grid item's 'xl', 'lg', 'md', ...

Switching between all tabs simultaneously in an MDX page (React + Gatsby + MDX) using @reach/tabs

Creating a Tab component for a Gatsby site has proved to be a bit tricky. Imagine having a page with multiple tabs all labeled the same: Heading 1 First tab block Tab 1 | Tab 2 Content Tab 1 Second tab block Tab 1 | Tab 2 Content Tab 1 for the second bl ...

Dynamically importing files in Vue.js is an efficient way to

Here's the code snippet that is functioning correctly for me var Index = require('./theme/dir1/index.vue'); However, I would like to utilize it in this way instead, var path = './theme/'+variable+'/index.vue'; var Inde ...

Increasing the Efficiency of Styled Components

It appears to me that there is room for improvement when it comes to checking for props in Styled Components. Consider the following code: ${props => props.white && `color: ${colors.white}`} ${props => props.light && `color: ${c ...

Customizing the font color and size of the MUI DatePicker default textfield is not supported

I'm encountering an issue with the MUI DatePicker as I am unable to customize the font color and font size of the date. Below is my code: const DateSettings = () => { const [value, setValue] = React.useState<Date | null>(); const handleC ...