Home > Software engineering >  How to pass key value pairs as parameters in Route Path?
How to pass key value pairs as parameters in Route Path?

Time:09-21

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?

CodePudding user response:

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\" 

CodePudding user response:

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:

      -  `this.props.history.replace("/location/"   this.props.color);`
    

Please read this article it will give you more ideas about react-redux react routes Article

or React routes documentation

  • Related