I am using React Router and the path params which I was passing has a "/", the react router taking that as seperate path and It was not redirecting


<Route exact path="/name/:username" component={Home}/>

while using that in other component, to redirect to this path, it is not redirecting because I was having "/" in the username(i.e., in the route param)

  const username = "/john/bradley"
  <Link to='name/username'>Click Here </Link>


If you want to conditionally match a route path that is either (1) a single "username" path segment or (2) a "firstname" segment then a "lastname" segment you’ll need to declare path matchers for both.


  path={["/name/:firstname/:lastname", "/name/:username"]}

Then form the link targets correctly.

Link to a "/name/john/bradly" ("/name/:firstname/:lastname"):

const username = "/john/bradley";

Link to a "/name/johnBradly" ("/name/:username"`):

const username = "/johnBradley";


<Link to={`name/${username}`}>Click Here </Link>

For something like a username field I’d suggest passing this as a queryString parameter so you void the need for odd route path matchers.


<Route exact path="/name" component={Home}/>

const username = "john bradley";


    pathname: 'name',
    search: `?username=${username}`,
  Click Here

Then in the Home component access the username from the location.search object string.

const { search } = useLocation();
const searchParams = new URLSearchParams(search);
const username = searchParams.get("username"); // "john bradley"

Answered By – Drew Reese

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published