1

I want to create an optional parameter url using react-router v4.2.0

I want the url to be like "/car-rental-service-in-manhattan-new-york" || "/car-rental-service-in-new-york";

Both url should render pages. Here manhattan is optional. I was trying the path like path: "/:keywords-in(-: boroughs)?-:city".

2 Answers 2

0

try like this

let city = window.location.pathname
    .replace('/car-rental-service-in-', '')
    .replace('-new-york', '');

{city ? (
  <Route
    path={'/car-rental-service-in-:city-new-york'}
    exact
    component={PageNotFound}
  />
) : (
  <Route
    path={'/car-rental-service-in--new-york'}
    exact
    component={PageNotFound}
  />
)}
Sign up to request clarification or add additional context in comments.

1 Comment

what if new york is also variable?
0

In order to restrict your parameters in your route, try the following solution.

<Route
   path="/car-rental-service-in-:city(york|newe)"
   component={City}
/>

To replace the space with hyphen,

    var str = this.props.match.params;
    str = str.replace(/\s+/g, '-').toLowerCase();

<Route
    path="/car-rental-service-in-:str "
    component={City}
/>

If you want to replace space with hyphen is many Components, then you can introduce Higher order component(HOC)

1 Comment

what i meant is like how to differentiate between manhattan and new york. also what if instead of manhattan some two or three letter word will come like '/car-rental-service-in-:abc-cde-efg-xyz-xyz' . abc cde efg is a name of single boroughs with space so i want '-' in place of 'space'. similarly xyz xyz is name of single city. how to differentiate the boroughs and city. so that abc-cde-efg comes in -:boroughs params variable and -xyz-xyz comes to :city params

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.