Search code examples
reactjsreact-router-dom

Is there a way to pass a param in a react route without using it in the url?


I want to make a route to a page that will change depending on what is stored in id. However, I also want the page URL to be entirely different from id. I currently have a working route: <Route path="/schedule/:url" element={<SchedulePage />} />. This properly sets the path to be "website.com/schedule/" + whatever is stored in url. Here is the issue: in my SchedulePage, I want to display information that I grab from id. The only way I can find to do so is with params, but I want to keep the id out of my url. How can I pass the id through the route as a param without including it in the url?

I tried changing the route to <Route path="/schedule/:url/:id?" element={<SchedulePage />} /> in the hopes that it wouldn't include the id, but that didn't work at all.

UPDATE:

I was able to find a solution with the help of STerliakov (See comments below to read our conversation.)

What I needed was the Mongoose function findOne(). Using this, I was able to do what I hoped to achieve; create a unique, user-defined String that fulfills the same purpose as _id (A unique anchor that can be used to find any one object.)


Solution

  • By using the Mongoose function .findOne, you are able to use a unique value to find an object. By setting your user's chosen String to something like url, you can use the following code:

    Schedule.findOne({url});
    

    This effectively makes a value just like _id that can be used to find a specific object, however the url value must be unique. This was not an issue in my case as I wanted to use the value to generate unique page URLs anyways. I've learned a lot in the past two hours.