简体   繁体   中英

How to conditionally route components in React?

In one of my React project, I have to route to specific components but, it has same links and different paramaters. Go through the code for clarity.

Home.js

{/* It links to Video Component */}
<div>
<Link exact to={{ pathname: `/contents/lists/${videoId}`}} />
<span>
...video section code
<span>
</div>

{/* It links to Photo Component */}
<div>
<Link exact to={{ pathname: `/contents/lists/${photoId}`}} />
<span>
...photo section code
<span>
</div>

JSON data as

const data = {
  contents: {
    lists: {
      id: 5abcd,
      photo: {
        cover: "url"
      }
    },
    lists: {
      id: 5xyz,
      video: {
        cover: "url"
      }
    },
  }
}

App.js

<Route exact path="/contents/lists/:photoId" component={PhotosComp} />
<Route exact path="/contents/lists/:videoId" component={VideosComp} />

Here PhotosComp extracts the params id properly but, for VideosComp params id for PhotosComp is extracted and gives error, it doesn't link to VideosComp. What could be appropriate solution?

const item Data = [
{
text: Photo,
link: `/contents/lists/:photoId`
},{
text: Video,
link: `/contents/lists/:videoId`
},

You can simply choose different routes:

<Route exact path="/contents/photos/:photoId" component={PhotosComp} />
<Route exact path="/contents/videos/:videoId" component={VideosComp} />

and update your links:

<Link exact to={{ pathname: `/contents/videos/${videoId}`}} />
<Link exact to={{ pathname: `/contents/photos/${photoId}`}} />

In your current code, no body can understand if /contents/lists/123456 should point to video component or the photo one.

Or if you must use same Route for some reason, then you can use some condition in your component:

<Route exact path="/contents/lists/:Id" component={MediaComp} />

And in MediaComp:

function MediaComp() {
    const id = ..... // todo
    if (some condition for video) 
      return <VideoComp/>
    else return <PhotoComp/>
}

Additionally, you can create links with some state data:

<Link exact to={{ pathname: `/contents/lists/${id}`, state: { type: 'photo' }}} />

And in MediaComp:

const type = history.location.state.type
if (type === 'photo) return <PhotoComp/> 
else.. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM