svnm
svnm

Reputation: 24318

In React Router how can I route to 2 similar urls with a different param

For example I have a <Song /> route which plays a song, and I want another route <SongInfo /> to show info on the song and another <SongComments /> to show the comments.

<Route path="songs" component={Songs} />
<Route path="song/:id/:name" component={Song} />
<Route path="songs/:id/:name/:info" component={SongInfo} />
<Route path="songs/:id/:name/:comments" component={SongComments} />

I want the url structure to look like the following:

/songs/123/cool_song/
/songs/123/cool_song/info
/songs/123/cool_song/comments

How do I achieve this? As currently the last 2 routes are the same and go to the same Component.

I am using react-router: 1.0.0

Upvotes: 1

Views: 168

Answers (1)

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

info and comments are static words or they are variables? I ask because in routes you use them as variables but in example you use them as static words. If they never change, then your routes should look like :

<Route path="songs" component={Songs} />
<Route path="song/:id/:name" component={Song} />
<Route path="songs/:id/:name/info" component={SongInfo} />
<Route path="songs/:id/:name/comments" component={SongComments} />

(I removed colon before info and comments). Now If you have url /songs/123/cool_song/info it will run SongInfo component. If you have url /songs/123/cool_song/comments it will run SongComments.

But if info and comments are variables which will be replaced by some string then the problem is with the last two routers that they are identical. Even if human have to decide e.g. /songs/123/cool_song/great-song, great-song is comment or info? You have to make them different. For example:

<Route path="songs" component={Songs} />
<Route path="song/:id/:name" component={Song} />
<Route path="songs/:id/:name/i/:info" component={SongInfo} />
<Route path="songs/:id/:name/c/:comments" component={SongComments} />

and your urls will look:

/songs/123/cool_song/i/great-song // info
/songs/123/cool_song/c/great-song // comment

Upvotes: 1

Related Questions