Home > front end >  How to navigate to a specific route without adding in the url in react
How to navigate to a specific route without adding in the url in react

Time:10-12

I'm using react-router and I have some routes nested like "/stories" and "/stories/:storyId" now my problem is that I have a component that is a single story and uses this specific storyId to navigate to the route "/stories/:storyId" on clicking it to see that story details. The problem comes that this single component can be rendered in another route like "/bookmarks" and if I use the hook useNavigate and pass it the storyId when I click the component it navigates to "/bookmarks/:storyId" and I want it to go to "/stories/:storyId"

CodePudding user response:

The component that is rendered on different subroutes should use absolute link paths instead of relative paths. The difference between relative and absolute paths is the leading "/" character. Paths starting with "/" are absolute from the root where the app is hosted, while paths otherwise are treated as relative from the current matched path.

For example, instead of

<Link to={`../${storyId}`}>{storyId}</Link>

... or ...

<Link to={`${storyId}`}>{storyId}</Link>

... or ...

navigate(`../${storyId}`);

... or ...

navigate(`${storyId}`);

which only links relatively to a sibling or child path from the current path, use an absolute path

<Link to={`/stories/${storyId}`}>{storyId}</Link>

... or ...

navigate(`/stories/${storyId}`);
  • Related