What is the process for appending a component to window.location.href?

I am working on implementing unique custom URLs for each item based on user interaction. After a user clicks "View Item", I want to redirect them to a URL that includes the item's name and ID, like this: "http://localhost:3000/item-1/-MC_xbIMm8zctEWRJ-Lj/". However, instead of the desired result, I end up with a blank page. The code snippet responsible for this functionality is as follows:

<Button style={{color: '#fff',display: 'flex', padding: 0, paddingLeft: "5px"}} startIcon={<AddShoppingCartIcon/>} 
onClick={() => this.routeChange(itemKeys[key].name,itemKeys[key].id )}> View Item </Button>

The function (routeChange) called upon clicking looks like this:

routeChange(name, id) {
var parameter1 = name.replace(/\s+/g, '-'); 
var parameter2 = id; 
window.location.href="/"+parameter1+"/"+parameter2+"/";
}

My current concern is how can I incorporate a component into this custom URL? I attempted something like the following:

<Route path="/${itemKey[key].name}/${itemKey[key].id}" component={Item} />

However, this approach did not yield the expected outcome, treating the variables as strings rather than routing correctly. Is there a way to include a component in the window location and avoid ending up with a blank page? Alternatively, are there better methods for creating custom URLs?

Answer №1

When setting up your Route, consider using a template literal for the path and a render prop for the component.

<Route exact path={`\${itemKeys[key].name/${itemKeys[key].id}`} 
    render={(props) => <Item {...props} />} />

Answer №2

For a practical demonstration of how to use URL parameters in React router, check out the example here. If you need URLs with dynamic variables, you can define a route similar to this:

<Route path="/:category/:itemID" component={ProductDetails} />

Once inside the ProductDetails component, you can access the category and item ID parameters using the useParams hook.

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

MERN Stack Application Error: Unable to set headers after they have already been sent to the client

Can someone help me with redirecting users after authentication based on their role using user.role? I am encountering the following error message: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...

React Hook Form is flagging missing dependencies in the useEffect function

Before posting this question, I made an effort to search for a solution on Google. However, I am puzzled by the warning that the linter is giving me regarding my code. The warning message reads: ./components/blocks/Contact.tsx 119:6 Warning: React Hook us ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

Alert: An invalid value of `false` was received for the non-boolean attribute `className`. To properly write this to the DOM, please provide a string instead: className="false" or use a different

While many have tried to address this issue before, none of their solutions seem to work for me... The error I am encountering is: If you want to write it to the DOM, pass a string instead: className="false" or className={value.toString()}. If ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

Having trouble with image URLs not working in React JS?

I am currently encountering an issue with displaying an image in my project. I have provided a relative path in the src properties, but unfortunately, it is not working as expected. If anyone has any suggestions or solutions to offer, please feel free to ...

Guide for utilizing a sitemap in Firebase hosting for a React application

I recently launched a reactjs web application on firebase hosting. To ensure better indexing by search engines, I created a sitemap.xml file and placed it in the public folder. Then, I made changes to my firebase.json file to redirect the source to the sit ...

Encountered an issue in Typescript with error TS2554: Was expecting 0 arguments but received 1 when implementing useReducer and useContext in React

I've encountered several errors with my useReducers and useContext in my project. One specific error (TS2554) that I keep running into is related to the AuthReducer functionality. I'm facing the same issue with each Action dispatch. I've tri ...

What are some alternatives for integrating React production build files apart from utilizing Express?

Is there a way to integrate React into my library using the HTTP module? I'm trying to figure out how to recursively send static files. Specifically, I want to include the build folder from the React production build, but I'm not sure how to go a ...

Having trouble uploading images using ReactJS on the web platform

I am currently in the process of developing a portfolio website using react js, but I'm experiencing an issue where the image I intended to display is not showing up on the live site. Despite thoroughly checking my code, I can't seem to identify ...

Toggle the visibility of the element or component with a simple click of a button

I am facing an issue where I am unable to change the state by clicking a button. Here is the code snippet in question: changeAllFun = () => { this.setState = ({ showBadTable: '1', }) } changeBadFun = () => { this.s ...

Troubleshooting issue with React mapping an array of items in a modal window

My state implementation is working perfectly fine, except for a minor issue with the modal window. Within the state, I have utilized objects that are normally displayed (you can refer to the screenshot here). Please pay attention to the "Open modal" butt ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

Using the Formik validation schema with Yup, determine whether the input is either "answer" or "another answer"

I'm trying to set up a form where if the region is "Europe" or "other", then certain fields are required. I've looked through the Formik documentation but haven't found a solution yet. <Formik enableReinitialize={true} initialValues={{ ...

Tips for dynamically loading a multitude of icons in Next.js

Is it worth loading these icons dynamically? import { faCheck, faCogs, faCoins, faCouch, faCreditCard, faGhost, faGift, faPuzzlePiece, faQrcode, faTasks, faVideo, faChild, faCubes, } from "@fortawesome/free-solid-svg-icons&qu ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

The MDX blog was set up to showcase markdown content by simply displaying it without rendering, thanks to the utilization of the MDXProvider from @mdx-js/react within Next JS

I'm currently in the process of setting up a blog using MDX and Next.js, but I've encountered an issue with rendering Markdown content. The blog post seems to only display the markdown content as plain text instead of rendering it properly. If y ...

The functionality of React Router is limited when it comes to handling nested URLs

I have been working on implementing a switch that routes different components based on the URL. The URL needs to support nesting, such as courses/:cid/assignments/:aid. Here is what my Switch setup looks like: <Switch> <Route path='/cours ...

Why is the lower sub-component positioned above the rest of the page?

I have set up a sandbox environment to demonstrate an issue that I am facing. The main problem is that when I click on "Option 1" in the main menu, a new component appears where a bottom sub-component (named BottomControls.js) is displayed at the top of t ...

Error: styled_default function is not defined in Grid2.js at line 5, column 26

Recently, I encountered an issue with the Material UI library when attempting to run React with Vite. Check out this image for more details. See another image here And one more image here as well. Despite multiple attempts of deleting and reinstalling th ...