dhavalnc1
dhavalnc1

Reputation: 139

How to use dynamic routing in React?

I am developing a dashboard application using React. I am having some issues understanding react-router. How can we use the dynamic route and render a component?

My app has a few static routes like /user, /profile and /dashboard. I am rendering User, Profile and Dashboard components for the routes. When the user logs in, the server will send JSON response which contains, user id, type, and other fields. I want to change the routing path to /dashboard/45 (45 is userId) for this user after a successful login. In the end, the Dashboard component will render different elements based on userId and userType.

<Route 
path='/dashboard'
exact={true}
render={(props) => <Dashboard {...props} user={user} handleChildFunc= 
{this.handleChildFunc}/>}/>

What is missing in this code? I am not sure what to google or which tutorial to follow. Thanks in advance.

Upvotes: 1

Views: 496

Answers (1)

Paddy
Paddy

Reputation: 625

This is what I use:

<Route exact path='/feed/:id' component={
  (props) =>
    <Feed
       postId={props.match.params.id}
    />
}/>

Then the id can be accessed inside Feed using props.postId e.g.

constructor(props) {
  super(props);

  if (props.postId) { 
    // do something
  }
}

Upvotes: 3

Related Questions