React Router - Why is my URL Param not working?

Zak Faithfull

I'm currently trying to route from a products page to an individual product page, however my URL param (:productName) isn't working. At present, the view stays on the Products component and just removes the list of products.

When the user selects a product from the products page, the view should switch to the Product component and display the title and product information.

I'd also appreciate any advice on how to structure the products section of my app - I have a number of products that all have different images and content. I'm fairly new to React so any information on how to structure this would be amazing!

App.js

import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./components/Home";
import WaterType from "./components/WaterType";
import Products from "./components/Products";
import Product from "./components/Product";

import "./App.css";

function App() {
  return (
    <div className="App">
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/waterType" component={WaterType} />
        <Route path="/products" component={Products} />
        <Route path="/products/:productName" component={Product} />
      </Switch>
    </div>
  );
}

export default App;

Products.js

import React from "react";
import { Link } from "react-router-dom";
import ProductData from "./data/ProductData";

const Products = ({ location }) => {
  const categorySelected = location.categorySelected;
  const waterType = location.waterType;

  const ProductsResult = ProductData.filter(x => x.categories.includes(categorySelected) && x.waterTypes.includes(waterType));

  return (
    <>
      <h1>Products</h1>
      <p>Current category: {categorySelected && categorySelected}</p>
      <p>Water Type: {waterType && waterType}</p>

      <div className="products">
          <ul>
            {ProductsResult.map((item, i) => (
              <li key={i}>
                <Link
                  to={{
                    pathname: '/products/' + item.slug,
                    name: item.name,
                  }}
                >
                  {item.name}
                </Link>
              </li>
            ))}
          </ul>
      </div>
    </>
  );
};

export default Products;

Product.js

import React from "react";

const Product = ({ location }) => {
  const productName = location.name;

  return (
    <>
      <h1>{productName}</h1>
    </>
  );
};

export default Product;
zixuan

Elaborating on the comments, list the longer routes before the shorter routes because if not, path=/products matches both /products and /products/:productName. It searches /products/ first and goes there instead of the other one.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related