The react documentation says that the match object contains a param property assigned to an object with Key/value pairs parsed from the URL corresponding to the dynamic segments of the path.
When I try to pass key value pairs as parameters, I only get the key, but the value is always undefined.
<Route path="/location:color?" component={Location} />
If I do this, and then in the Location component, I console log props.match, I get the match object, but when I open it, I get this: params: {color: undefined}.
How do I pass value too?
Also, I feel like I'm misunderstanding something about these path parameters, because what exactly is the point of them? If I wanted to pass any value to any component, I can just use props. What is the purpose of these path parameters?
For all complex data structures, I recommand parsing to string and deserialize at the other end. it may be a good practice if everyone in your team is doing it this way.
Example :
KeyValuePair : <Color,Blue>
Parse it to string : "\"Color\",\"Blue\"
The idea of using path="/location/:color?":
is to fetch/navigate to a page according to its id to get information
For example, I want to get student information on the page, first, it goes to URL www.location/studentId it will take the student id to know which student to view on the page.
In your case, you get undefined because you didn't pass any color value, so you need to pass the value to navigate as follow:
- change `<Route path="/location:color?" component={Location} />`
to `<Route path="/location/:color?" component={Location} />`
- To navigate use `this.props.history.replace("/location/" + this.props.color);`
Please read this article it will give you more ideas about react-routesreact routes Article
or React routes documentation
Related
I have a book item and I want to assign two routes for it. Is it possible with react? For example, when I click the item from the homepage route should be 'books/:id'. If I checked the book from a specific category page the route should be 'books/categoryName/:id'. Thank you in advance.
Yes, a Route's path property accept either string or string[]. See the docs
What do colon and dollar given below mean in React?
Example for colon:
<Route path={'/movie/:id'} component={Movie} />
Example for dollar, (its used right before the expression but why):
<Link to={`/movie/${this.state.movies[index].id}`} key={index} className="movieLink">
$ is not of react. But its ES6 feature called template literals more at Template Literals basic or template literals.
In react, you have Route and Link components in react router module.
Route takes two properties: path and component. When a path matches the path given to the component, it will return the component specified
In your Route, you are saying to match any path which is of movie/anyid which means it navigates to the component specified (here Movie) with the given parameter
Link is used to specify which path to go to. Its just a wrapper of <a> tag and helps in navigating to the specified path and in your current example, its to /movie/1 (assuming this.state.movies[index].id is 1)
Well its a JavaScript ES6 feature ,
As you can imagine before ES6 you can do something like :
var user = 'xyz' + newuser;
ES6:
var user = `xyz${newuser}`;
Template literals are enclosed by the back-tick (``) , Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).
You can read more about Template literals on Mozilla
I too have spent ages trying to find out how the colon works. It's pretty frustrating to have to try and reverse engineer the examples rather than having it explained in the API section.
Having said that, there is a hint in the documentation https://reacttraining.com/react-router/core/api/Route where it says that the path accepts "Any valid URL path or array of paths that path-to-regexp#^1.7.0 understands". If you look at the documentation for path-to-regexp you can see that "Named parameters are defined by prefixing a colon to the parameter name ... By default, the parameter will match until the following path segment"
Then you can look at https://reacttraining.com/react-router/core/api/match which explains how to get hold of a match object and how you can extract the parameters from it.
The dollar is an es6 syntax to use variables in strings.
The : is, in this case, part of the path-to-regexp syntax used by React Router (and Express) for paths; it allows you to specify a parameter. This has two implications.
To match multiple urls.
<Route path='/app/:page'>
Will match any /app/ followed by anything.
Note that there are flexible match types here, but they're not typical regex, exactly: https://github.com/pillarjs/path-to-regexp/tree/v1.7.0
The second purpose of this is to make the parameter (whatever comes after /app/) available, via React Router's useParams hook (https://reactrouter.com/web/api/Hooks/useparams).
For a good example of the syntax, check out the "Route Parameters" section on this page:
https://expressjs.com/en/guide/routing.html
I'm trying to figure out where in the location.search object the query params are:
Code:
const params = new URLSearchParams(this.props.location.search);
console.log(params);
URL:
http://localhost:3000/detail/8?abc=20
Chrome Console:
Where should I traverse to find params in the URLSearchParams object tree in the Console?
Also is there a find or search feature in the Console that lets me figure out the location of something? It's like an endless tree.
There are various ways of accessing the parameters via the API, I'm guessing get, getAll, or keys are what you need. The reason you don't see values directly in the console is that these are methods, not attributes, so they need to be executed for you to see the actual data.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
This question isn't really a ReactJS question, unless you're having trouble with the this.props.location.search object itself, in which case you should post its source/parent component.
Using React with React-Router in a project and am wondering if it's possible to limit the possibilities for param names, like so:
www.mydomain.com/books/:id
and allowing 'Catcher in the Rye' and 'To Kill A Mockingbird' to be passed through, like so:
www.mydomain.com/books/catcher-in-the-rye
www.mydomain.com/books/to-kill-a-mocking-bird
I want to say that only a specific set of books can be used in place of :id (just so someone can't type in www.mydomain.com/books/whatever-they-want and have an empty React component render).
I do currently have a '*' route that catches anything not mentioned, but because params are dynamically generated based on whatever is passed, that won't help in this case.
Is this possible? Thanks.
You need to handle this logic in the component. Depending on if this is an already mounted component or not you will need to put the logic in the appropriate function (componentDidMount, componentWillReceiveProps)
if(!(this.props.params.id in myAcceptableParameters)){
redirect to a 404 here
}
I would like to implement finite netsing of ui router states (it is required by the client), the maximum depth of nesting can be a fixed value (for example 10) therefore i would like my states to look as such:
.state('page',{url:'page/{pageName}',templateUrl:...)
.state('page.page',{url:'/{pageName}',templateUrl:...)
.state('page.page.page',url:'/{pageName},templateUrl:...)
etc...
In the end i would like for user to be able to enter urls like:
'/page/page1/subpage1'
'/page/page2/subpage1/subsubpage2'
'/page/page3'
etc...
The obvious problem is that ui router will overwrite the 'pageName' variable for each (sub)state, therefore after navigating to /page/page1/subpage1 i will only have {pageName:'subppage1'} variable set in state 'page' and 'page.page'.
In the whole application the ui-sref would only use the RELATIVE states so when i am in the 'page' state i would go into 'page.page' state and so on. I would like to be able to move the html view of the page up or down the state hierarchy as needed, and i would like not to change every ui-sref call in such case (right now i would have to change the variable name because it has to have different name in every state)
Is there any possibility to achieve my desired scenario? i have tried defining 'pageName' as an array type, but it does not seem to work (gets overwriten for every substate). Using custom ui router type also seems to not work since it cannot modify stateParams objects, only returns the representation of single url value (therefore the 'pageName' is also overwritten).
Ui-router extras also seems not to help here, or maybe i am missing something.