Lee Probert
Lee Probert

Reputation: 10859

How to deal with a query parameter in react router

I have a URL structure like so http://localhost:3001/article?id=12345 and I want to route the article ID parameter into a React Component. My Route is like this <Route path="/article?id=" component={ArticleDetail}/> and at the moment I am just trying to get it to print out the value of the parameter in my component like so:

class ArticleDetail extends Component {
    render() {
        const {location} = this.props.location;

        return (
            <div>
                <h2>Article Detail</h2>
                <p>This will show the full Article detail</p>
                <p>props: {location}</p>
            </div>
        );
    }
}
export default ArticleDetail;

I'm not seeing the component rendered at all though. What is the Route I need to get it to load the component so I can then strip out the parameter value?

Upvotes: 1

Views: 4095

Answers (1)

trixn
trixn

Reputation: 16354

I wouldn't match query parameters already in the path of your Route. Query parameters are just key/value pairs and could appear in random order. Matching them in the route would already make assumptions about their order.

<Route path="/article" component={ArticleDetail}/>

In ArticleDetail you can get the query parameter like that:

const id = URLSearchParams(this.props.location).search.get('id');

But usually you don't use query parameters anyway when dealing with ids that identify an entity. You would rather have a path like: /article/12345 where 12345 is the article id:

<Route path="/article/:id" component={ArticleDetail}/>

Then you could access it simply like that:

const {id} = this.props.match.params;

Upvotes: 3

Related Questions