Ryne
Ryne

Reputation: 1415

Render component based of parameter in path

For my project I want to render a user's page at url.com/username .. if the username of the logged in user matches the parameter then it'll render their profile page. So in my router I have this route...

<Route path="/:username" exact component={/* Profile or User's Page */}>

I have other routes where the components are conditional and I use a ternary in the component, however in this case it would be based off the :username parameter. Is there a way to access that value within the component tag? Or should I have some sort of HOC in the component tag where I can compare the :username parameter to authenticated username and then return the Profile or UserPage component?

Upvotes: 0

Views: 1403

Answers (1)

Lukas Bach
Lukas Bach

Reputation: 3909

You can access the URL parameters using the component prop match.params.:param

<Route
  path="/:username"
  component={Component}
/>

const Component = ({ match }) => (
  <div>
    <h3>{match.params.username}</h3>
  </div>
);

If you want to access the parameter inside the component parameter, you could for example use an anonymous component (or just have a component especially for determining which subcomponent would be used).

<Route path="/:username" 
       component={({match} => {
         if(match.params.username == this.props.username) {
           return <SomeComponent />
         } else ...
       })} 
/>

Upvotes: 1

Related Questions