Reputation: 2750
I am using query-string to pass some parameters and render the below component
import React, { Component } from "react";
class Show extends Component {
constructor(props,context) {
super(props,context);
this.state = {
name: ''
};
console.log(this);
}
render() {
return (
<div>
<h4>Hi {this.props.match.params.name} </h4>
<p></p>
{this.props.match.params.name ? <b>ID: {this.props.match.params.name}</b> : }
</div>
);
}
}
export default Show;
The route is like below :
<Route path='/show/:name?' component={Show} />
But this always results in undefined name and I see only Hi not the name .I use the below versions .
"react-dom": "^16.13.0",
"react-router-dom": "^5.1.2",
"query-string": "^6.11.1"
Not sure where I am making a mistake .Any help is appreciated.
Upvotes: 0
Views: 2157
Reputation: 3012
Query string is used with a longer URL with something after the "?". If i type in localhost:3000/show/bob?
the props.location object would have the pathname as /show/bob
, so you don't really need it for this specific route.
I reproduced your code locally and wasn't getting 'undefined' for name, I was getting the expected output. Make sure that your App component routes are surrounded by a <Router>
tag like this:
<Router>
<Route path='/show/:name?' component={Show} />
</Router>
Also the if/else conditional in your show component needs something after the else operator. Either use && or add null
after it.
If you're interested in hooks check out the useParams() hook here. It provides url parameters for you.
Upvotes: 0
Reputation: 203476
You can query path query parameters from the location
prop.
props.location.search
If route path is "/show/:name"
, the match
prop will have the path parameter name
, i.e. props.match.params.name
, and any URL query parameters will simply be appended to the URL and can be found on the location
prop.
Usage:
class Show extends Component {
constructor(props, context) {
super(props, context);
this.state = {
name: ""
};
console.log(this);
}
render() {
return (
<div>
<h4>Math Param {this.props.match.params.name} </h4>
<h3>Query {this.props.location.search} </h3>
<p />
{this.props.match.params.name && (
<b>ID: {this.props.match.params.name}</b>
)}
</div>
);
}
}
Upvotes: 1