How to match arbitrary text after a route with react-router - reactjs

I am transition a route from another application that is defined as /locations/(.*).
The other application supports URLs such as /locations/country=usa&size=large, rather than your typical query string format of /locations?country=usa&size=large. I'd like to mimic that.
I know that react-router routes are parsed by path-to-regexp, which seems to support arbitrary regex in the routes, but my component does not render with the following defined route:
<Route path="/locations/(.*)" component={Locations} />
What's the correct way to support arbitrary text after a route, rather than your traditional query string?

You can use a named query parameter in your route, parsing the query parameter in the locations component and displaying content relevant to the query params.
For example...
<Route path="/locations/:locationPath" component={Locations} />
and then in the Locations component
constructor(props) {
super(props);
const locationPath = props.match.params.locationPath;
// conditionally do something based on locationPath
}
You can do this in the constructor, or componentWillMount, componentDidMount or any variation therein. I do mine in the constructor as this is the earliest access to the props object and state.
If you're more certain of the possibility in the query string you can use
<Route path="/locations/country=:country,state=:state" component={Locations} />
and you will receive country and state as separate keys in the match.params object.
Finally, if you don't want to require each param you can use the following
<Route path="/locations(/?country:country)(/?state=:state)" component={Locations} />
and you will get this route whether state or country is specified alone, or together.
React Router v4 Route

Related

React router with multiple params

I have a page route /movies?categoryId=21213
on this page, I have a section of actors, on the click it's should redirect to /movies?categoryId=21213/actor?actorId=234324234
how should I describe correctly to render my latest component with an actor?
I tried
<Route path=`/movies/:categoryId?/:actorId?`/>
but that's not working
There are two ways to approach this. Either go with query params or path params.
Path params
You route:
<Route path='/movies/:categoryId/:actorId' />
Here you will have route that has two path params /movies/1/2.
Query params
Your route
<Route path='/movies' />
So your route is only /movies but you pass query params to it and handle them in your component.
Example of a route with query params /movies?categoryId=1&actorId=2.
You can use useHistory hook for that purpose in your routed component.
Personally i preferred to use query params because they are easier to handle in your component, but you can pick your way from these two examples.
In your question, code is a bit wrong, because path params dont need ? to be present in a route.

ReactRouter: Capture part of path and specify a value to match at the same time

I have a path in the format of /somePath/:name where the :name needs to be one of the known strings. I read that the Route component supports an array of URLs to match, so it's easy to generate a list of supported paths, but doing so takes away the convenient of automatically capturing the part of the path.
For example, I currently have a Route component defined like this below.
<Route exact path={SomeKnownNames.map(n => `/somePath/${n}`)} component={SomeRoute} />} />
This should work, but I cannot access the value in props.match.params in the Route component anymore. Is there a way to achieve this without manually parsing the URL?
Let me add that I do NOT want to match if the value of :name is not in the known strings.
I'm using react-router-dom v5.
Apparently, this works:
<Route exact path={SomeKnownNames.map(n => `/somePath/:name(${n})`)} component={SomeRoute} />} />
i.e. If you do /somePath/:name(foo), then it matches /somePath/foo, and foo is captured in props.match.params.name in the route component.
Have you tried doing this:
path={SomeKnownNames.map(n => `/somePath/:${n}`)}
Adding the : allows the names to be treated as params. Try it out, let me know if that is unrelated. I may need more information to better answer your question.
Also, try to use the useParams() hook from React Router. What does it show in your component?
Update: path-to-regexp was removed from React V6, so this answer is obsolete.
React Router uses the path-to-regexp library, which allows you to provide your own regex for a parameter. See https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#custom-match-parameters.
For example, if you want to match /somePath/foo, /somePath/bar, and /somePath/baz, and have match.params contain myParam: "foo", myParam: "bar", or myParam: "baz", use this pattern:
<Route
exact
path="/somePath/:myParam(foo|bar|baz)"
component={SomeRoute}
/>

how to have the same route path hit different components

I'm having an issue with react router and its routing path.
I have a couple of links, say
localhost:3000/a
localhost:3000/b
localhost:3000/c
and my route is set up as so:
<Route exact path="/:cat" component={Post} />
My issue is that whenever I go to one of the three URLs, i.e. 1 -> 3, it will only load page 1, as all of them meet the criteria (i.e. path="/:cat"). Am I correct to assume that it won't render each path as they are referred to as ONE route, hence it doesn't need to be rendered as the "state" hasn't changed?
Its one route and any matching path (/a or /b) will render that Post component.
<Route exact path="/:cat" component={Post} />
This route will allow you to render Post component for each url, that starts from / and this component will have the actual url inside this.props.routeParams.cat.
You can use this prop in your Post component to call the appropriate child component. i.e Check if this.props.routeParams.cat = a , then call <ComponentA />.

ReactJS Values In The URL Always Visible

I have a filter system for my products in ReactJS which basically has the following:
http://localhost:3000/category/women/subcategory/tops/sorting/null/price/null/size/null/color/null/brands/null/merchants/null
The Route is as follows:
<Router>
<Route path="/category/:cat/subcategory/:subCat/sorting/:sorting/price/:price/size/:size/color/:color/brands/:brands/merchants/:merchants" component={Products} />
</Router>
The Problem is that I want to show filters in the URL in when they have a value other than null. Current my component works but I have to display every single filter in the URL with a null value by default, this is causing my URL to be extremely long. The only way I thought possible was to do a permutation combination of all the possible URLs in the filter and direct them all to { Products } which is extremely silly. There must be something in the Router component that I'm missing?
You need to use optional params in this case.
As and example if you want to accept both sorting/ascending/price and sorting/price you can write your path as follows assuming you use react router v4.
<Router>
<Route path="sorting/:sort?/price" component={Products} />
</Router>
You can read more about this here: React Router with optional path parameter

Using multiple params with React Router?

<Route path="/:user" component={Home}>
<Route path="/:thing(/:version)" component={Thing}/>
</Route>
So, I've got two dynamic objects in my application that I'd like to be controlled by route params in react-router. Using the code above, both /0 and /0/3 take me to Home. I need /0/3 to take me to Thing. I'm not sure what I'm doing wrong here... Does react-router even support multiple dynamic params next to each other like this? I couldn't find anything in the docs.
What happens here is that you've given React Router two paths that can both match on /anything. By default then React Router matches the first one it can find.
To dig deeper, if I go to /pudding, React Router can't know if you meant /:user or /:thing. Since /:user occurs first, that option will be chosen.
You also need to make sure if nesting routes is what you want. Currently, your Thing route is nested below Home, which means that it is rendered via this.props.children in your Home component. So, for your current Thing route, Home will always be rendered too, with Thing as a child. If your Home component doesn't render this.props.children, Thing will not be shown.
I suspect you just want two different pages. What you could do to achieve that is the following:
<Router history={history}>
<Route path="/user/:user" component={Home} />
<Route path="/:thing(/:version)" component={Thing}/>
</Router>
This will make every /user/name go to the Home component, and every other /random (with an optional extra level) will go to Thing. If you wonder why in this case React Router doesn't take /user/name to the Thing route, it's because it still matches in the order your routes are specified. Because your Home route matches the requested URL, no siblings of this route are tested anymore.

Resources