Adrian
Adrian

Reputation: 190

react-router parameterize redirect

I'm having trouble figuring out how to parameterize a route string for programmatically redirecting.

my setup in /constants/routes.js

export defaults {
  user_details: '/user/:id/details',
}

I would like to push the :id parameter programmatically as

import routes from '../../constants/routes.js'
const UserListItem = ({name, id, history}) => (
  <li onClick={ () => history.push(routes.user_details, {id}) }>
  {name}
  </li>
)

The internet seems to be filled with <Redirect to={/user/${id}/details} /> which doesn't seem optimal as I would like to reuse my constant route

Upvotes: 0

Views: 21

Answers (1)

lecstor
lecstor

Reputation: 5707

depends on how you are using these route constants I guess. An I'm not sure what you mean by "bypass any rules" either, but you could maybe change your constants to be functions.

export defaults {
  userDetails: (id = ":id") => `/user/${id}/details`,
}

usage:

path={routes.userDetails()} -> `/user/:id/details`

history.push(routes.userDetails("abc123")) -> `/user/abc123/details`

Upvotes: 1

Related Questions