0

I have a filter system for my products in ReactJS which basically has the following:

http://localhost:3000/category/women/subcategory/tops/sorting/null/price/null/size/null/color/null/brands/null/merchants/null

The Route is as follows:

<Router>
    <Route path="/category/:cat/subcategory/:subCat/sorting/:sorting/price/:price/size/:size/color/:color/brands/:brands/merchants/:merchants" component={Products} />
</Router>

The Problem is that I want to show filters in the URL in when they have a value other than null. Current my component works but I have to display every single filter in the URL with a null value by default, this is causing my URL to be extremely long. The only way I thought possible was to do a permutation combination of all the possible URLs in the filter and direct them all to { Products } which is extremely silly. There must be something in the Router component that I'm missing?

Preview
  • 35,317
  • 10
  • 92
  • 112
Aayush
  • 3,079
  • 10
  • 49
  • 71
  • why putting `null` in url, instead of that check the value and assign some default like **-** if value is `null`. – Mayank Shukla May 20 '17 at 07:37
  • Sure I can change null to all or whatever, but is it necessary to have it in the URL unless it has a value other than null or all. – Aayush May 20 '17 at 07:39
  • i think, you have to because you defined all of them as url parameters so to assign proper value to correct param you need to put some default or null, otherwise if you skip that null, next values will get assigned to wrong param. – Mayank Shukla May 20 '17 at 07:44

1 Answers1

0

You need to use optional params in this case.

As and example if you want to accept both sorting/ascending/price and sorting/price you can write your path as follows assuming you use react router v4.

<Router>
  <Route path="sorting/:sort?/price" component={Products} />
</Router>

You can read more about this here: React Router with optional path parameter

Community
  • 1
  • 1
Tharaka Wijebandara
  • 7,955
  • 1
  • 28
  • 49