I have a problem with passing parameters inside the route. Currently, I have these routes:
<Route component={CategoriesPage} path={`/${AllRoutesEnum.COURSES}`} exact/>
<Route component={CoursesPage} path={`/${AllRoutesEnum.COURSES}/:id`} exact/>
<Route component={SectionPage} path={`/${AllRoutesEnum.COURSES}/:id/:id`} exact/>
So SectionPage route will look like this: courses/k-8-grades/early-math
What I want to do:
- When the section page reached add a new id parameter. Video lesson id. So it should be: courses/k-8-grades/early-math/videoId
- When clicking button overview. Add url #overview. So it should be courses/k-8-grades/early-math/videoId#overview.
- When clicking button search. Remove url #overview add #search. So it would be courses/k-8-grades/early-math/videoId#search
So what I tried:
- Using redirects. When reached SectionPage somehow pass id to redirect. But it failed because routes didn't match properly.
<Redirect from={`/${AllRoutesEnum.COURSES}/:id/:id/`} to={`/${AllRoutesEnum.COURSES}/:id/:id/test`} />
{/* courses/early-math/early-math/test */}
<Route component={SectionPage} path={`/${AllRoutesEnum.COURSES}/:id/:id/`} exact/>
{/* courses/k-8-grades/early-math */}
- In Section Page add lesson id onInit. But if I manually add it
import { useHistory } from "react-router-dom";
const history = useHistory();
history.push('fdfdf');
When it would become courses/k-8-grades/fdfdf instead of courses/k-8-grades/early-math/fdfdf
Update So what I came up with doing is creating a SectionRedirect page:
<Route component={CategoriesPage} path={`/${AllRoutesEnum.COURSES}`} exact />
<Route component={CoursesPage} path={`/${AllRoutesEnum.COURSES}/:a`} exact />
<Route component={SectionRedirectPage} path={`/${AllRoutesEnum.COURSES}/:a/:b/`} exact />
<Route component={SectionPage} path={`/${AllRoutesEnum.COURSES}/:a/:b/:id`} exact />
Section redirect page pushes videoID. Because I need to pathname before fetching correct video id courses/k-8-grades/early-math.
props.history.push(`${location.pathname}/${videoId}`);
In section page, I used like suggested and it worked wonders.
props.history.push({ hash: "overview" })
Unfortunately, it didn't fully solve my problem: Expected behavior: Currently when visiting section Page my url is this:
courses/k-8-grades/early-math/videoId1#overview
Clicking on second video link should change url to this:
courses/k-8-grades/early-math/videoId2#overview
Real life example would be udemy video player.
Found solution using: In section.page
history.push({
pathname: '/courses/k-8-grades/early-math/videoId'
})
question from:https://stackoverflow.com/questions/65661584/react-router-routing-with-parameter-id