Home > Enterprise >  Parameters Routing
Parameters Routing

Time:12-03

I'm having a problem in getting the output of the "match" object value in this parameter routing code.

This is class where I use match:

import React from "react";

const ProductDetails = (props) => {
  console.log(props.match);
  return <h1>Details No. </h1>;
};

export default ProductDetails;

And the code I use for using the route is:

import React, { Component } from "react";
import NavBar from "./navbar";
import ProductDetails from "./productDetails";

class App extends Component {
  render() {
    return (
      <React.Fragment>
        <NavBar
          productsCount={this.state.Product.filter((p) => p.count > 0).length}
        />
        <main className="container">
          <Routes>
            <Route path="/about" element={<About />} />
            <Route path="/" element={<Home />} />
            <Route path="/contact" element={<Contact />} />
            <Route
              path="/cart"
              element={
                <ShoppingCart
                  products={this.state.Product}
                  onReset={this.resetData}
                  onIncrement={this.incrementEntry}
                  onDelete={this.deleteEntery}
                />
              }
            />
            <Route path="/products/:id" element={<ProductDetails />} />
          </Routes>
        </main>
      </React.Fragment>
    );
  }
}

And I get the answer as "undefined" and a lot of red errors msgs.

CodePudding user response:

if you are using react router v6 and what you want to do is getting the id, it would be:

import React from "react";

const ProductDetails = () => {
  const {id} = useParams();
  return <h1>Details No. {id}</h1>;
};

export default ProductDetails;

or if you really want the match object:

import React from "react";

const ProductDetails = () => {
  const match = useMatch();
  return <h1>Details No.</h1>;
};

export default ProductDetails;

CodePudding user response:

What is element? If you use react-router-dom for routing you must set the component for any route.

<BrowserRouter>
    <Route path ="/about" component= {<About />} />
    <Route path ="/" component= {<Home/>}/>
    <Route path ="/contact" component= {<Contact/>}/>
    <Route path ="/cart" component= {<ShoppingCart 
        products= {this.state.Product}
        onReset ={this.resetData}
        onIncrement ={this.incrementEntry} 
        onDelete = {this.deleteEntery}/>}/>
    <Route path="/products/:id" component={<ProductDetails />}/>
</BrowserRouter>
  • Related