How to parse a query string in React Router

后端 未结 3 1681
不思量自难忘°
不思量自难忘° 2021-02-20 08:39

Hello I´m using react router and I need to pass some querystring parameters

tried with



        
3条回答
  •  难免孤独
    2021-02-20 09:35

    For url parameters, like /animals and /cars, you can use the colon syntax /:type

    But for query parameters, like ?filter=something, you need to parse the query string.

    According to react-router docs:

    React Router does not have any opinions about how your parse URL query strings. Some applications use simple key=value query strings, but others embed arrays and objects in the query string. So it's up to you to parse the search string yourself.

    In modern browsers that support the URL API , you can instantiate a URLSearchParams object from location.search and use that.

    In browsers that do not support the URL API (read: IE) you can use a 3rd party library such as query-string.

    For example, in your component you will have location as a prop from the parent Route (or you can get it from withRouter), you can then use location.search to parse the query string like this:

    function Parent({location}) {
      let params = new URLSearchParams(location.search);
    
      return ;
    }
    

    For more info:

    • React Router Docs - Query Parameters

    • Example CodeSandbox

提交回复
热议问题